c++ - 从二进制图像 OpenCV C++ 中裁剪文本

标签 c++ opencv crop

如何使用 OpenCV 裁剪图像,使图像中只包含文本? enter image description here

最佳答案

方法

  1. 在垂直和水平方向上放大图像
  2. 寻找边界矩形
  3. 裁剪图片

代码

# reading the input image in grayscale image
image = cv2.imread('image2.png',cv2.IMREAD_GRAYSCALE)
image /= 255
if image is None:
    print 'Can not find/read the image data'
# Defining ver and hor kernel
N = 5
kernel = np.zeros((N,N), dtype=np.uint8)
kernel[2,:] = 1
dilated_image = cv2.dilate(image, kernel, iterations=2)

kernel = np.zeros((N,N), dtype=np.uint8)
kernel[:,2] = 1
dilated_image = cv2.dilate(dilated_image, kernel, iterations=2)
image *= 255

# finding contours in the dilated image
contours,a = cv2.findContours(dilated_image,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# finding bounding rectangle using contours data points
rect = cv2.boundingRect(contours[0])
pt1 = (rect[0],rect[1])
pt2 = (rect[0]+rect[2],rect[1]+rect[3])
cv2.rectangle(image,pt1,pt2,(100,100,100),thickness=2)

# extracting the rectangle
text = image[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]

plt.subplot(1,2,1), plt.imshow(image,'gray')
plt.subplot(1,2,2), plt.imshow(text,'gray')

plt.show()

输出

Figure1-Dilated Image

Figure2-Bounding Rect

Figure3-Cropped Image

关于c++ - 从二进制图像 OpenCV C++ 中裁剪文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23125359/

相关文章:

C++ 随机种子、全局对象和 SDL_Threads

c++ - 与 stringstream 的链接错误

image - OpenCV cv::Mat 显示空的灰色图像?找不到原因

c++ - 排序链表和addSorted函数问题。

c++ - 如何在 C++ 中对字符串进行哈希处理?

javascript - ImageStore.addImageFromBase64 的替代方案?

c# - 如何在 monotouch Xamarin 中裁剪图像

swift - 如何快速裁剪所选区域的视频帧大小?

c++ - C++ 中 std::fstream::X 和 std::ios::X 的区别

python - 从 python Opencv Videocapture 接收 Gazebo gstreamer UDP 视频