[英]How to detect a rectangle block from an image and change it to white color?
Here is one way to do that in Python/OpenCV.这是在 Python/OpenCV 中执行此操作的一种方法。
Input:输入:
import cv2
import numpy as np
# read image
img = cv2.imread('black_rectangle.png')
ht, wd = img.shape[:2]
print(img.shape)
# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# threshold
thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)[1]
# invert
thresh = 255 - thresh
# get largest external contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
# get bounding box of largest contour
x,y,w,h = cv2.boundingRect(big_contour)
# make that region white in the input image
result = img.copy()
result[y:y+h, x:x+w] = (255,255,255)
# show thresh and result
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save resulting image
cv2.imwrite('black_rectangle_2white.png',result)
Result:结果:
Changing a rectangle to a certain color is the easy part, detection is harder.将矩形更改为某种颜色是容易的部分,检测更难。
You could try for each black pixel to group it with neighboring pixels of the same color.您可以尝试将每个黑色像素与相同颜色的相邻像素分组。 Once you have these groups, you need to find out if it's a rectangle or something else, eg a letter or a line.
拥有这些组后,您需要确定它是矩形还是其他东西,例如字母或线条。
A rectangle would have a minimum size, a convex outline and its area should be fully black.一个矩形有一个最小尺寸,一个凸的轮廓,它的区域应该是全黑的。
For each group that fulfills these conditions, replace its pixels with white ones.对于满足这些条件的每个组,将其像素替换为白色像素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.