繁体   English   中英

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

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

如何从下面这样的图像中删除黑色矩形,

在此处输入图像描述

我想检测那个巨大的黑色矩形框并将其更改为白色? 这是我的下一个预处理阶段。

任何帮助表示赞赏

这是在 Python/OpenCV 中执行此操作的一种方法。

  • 读取输入
  • 转换为灰色
  • 二进制和反转的阈值
  • 获得最大的外轮廓
  • 获取该轮廓的边界框
  • 用白色填充输入的那个区域
  • 保存结果

输入:

在此处输入图像描述

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)

结果:

在此处输入图像描述

将矩形更改为某种颜色是容易的部分,检测更难。

您可以尝试将每个黑色像素与相同颜色的相邻像素分组。 拥有这些组后,您需要确定它是矩形还是其他东西,例如字母或线条。

一个矩形有一个最小尺寸,一个凸的轮廓,它的区域应该是全黑的。

对于满足这些条件的每个组,将其像素替换为白色像素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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