简体   繁体   English

如何从图像中检测矩形块并将其更改为白色?

[英]How to detect a rectangle block from an image and change it to white color?

How can I remove a black color rectangle from an image like this below,如何从下面这样的图像中删除黑色矩形,

在此处输入图像描述

I want to detect that huge black color rectangle box and change it to white color?我想检测那个巨大的黑色矩形框并将其更改为白色? Its my next pre-processing stage.这是我的下一个预处理阶段。

Any help is appreciated任何帮助表示赞赏

Here is one way to do that in Python/OpenCV.这是在 Python/OpenCV 中执行此操作的一种方法。

  • Read the input读取输入
  • Convert to gray转换为灰色
  • Threshold to binary and invert二进制和反转的阈值
  • Get the largest external contour获得最大的外轮廓
  • Get the bounding box for that contour获取该轮廓的边界框
  • Fill that region of the input with white用白色填充输入的那个区域
  • Save the result保存结果

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM