Trim text from OpenCV C ++ binary image

How can I crop an image so that only text is included in the image using OpenCV? enter image description here

+1
source share
3 answers

An approach

  • Zoom out vertically and horizontally
  • Search bounding box
  • Image cropping

the code

# 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()

Output

Figure1-Dilated Image

Figure2-Bounding Rect

Figure3-Cropped Image

+7
source

Assuming you have pixel information, you can draw a convex body around white text. After that, you have the body, you can get the lowest and highest x and y coordinates and use them as the coordinates of the rectangle so that you can crop the rest of the image.

, Open_CV (++), .

, (, erosion), .

0

Take the projection of the white pixels in the x and y directions. The lowest and highest values ​​in the x and y direction are related by your y and x rectangles, respectively. This solution is for simple situations with low processing and on-site computing.

0
source

Source: https://habr.com/ru/post/1543290/


All Articles