我的输入图像
提取高亮部分
我想要的输出
请有人帮助并给我一个建议。我的图像看起来像这样。这只是示例之一。我需要裁剪底部模板部分并进行 OCR。我附上了我想要的输出图片。请看一看。如何用python实现?
PS:板材尺寸会有所不同,模板有可能错位。但大部分会在左下角
这是一个可能的方法:
获得二值图像。我们转换为灰度,高斯模糊,然后是 Otsu 的阈值
填充潜在的轮廓。我们遍历轮廓并使用轮廓近似进行过滤以确定它们是否为矩形。
执行形态学操作。我们变形开放以使用矩形内核移除非矩形轮廓。
过滤并提取所需的轮廓。使用轮廓近似、纵横比和轮廓区域查找轮廓并进行过滤以隔离所需的轮廓。然后使用 Numpy 切片提取。
- 二进制图像
- 填充轮廓
- 去除非矩形轮廓的形态学操作
- 所需轮廓以绿色突出显示
提取的投资返回率
代码
import cv2
# Grayscale, blur, and threshold
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Fill in potential contours
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.05 * peri, True)
if len(approx) == 4:
cv2.drawContours(thresh, [c], -1, (255,255,255), -1)
# Remove non rectangular contours
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40,10))
close = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Filtered for desired contour
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.05 * peri, True)
x,y,w,h = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
area = cv2.contourArea(approx)
if len(approx) == 4 and w > h and aspect_ratio > 2.75 and area > 45000:
cv2.drawContours(image, [c], -1, (36,255,12), -1)
ROI = original[y:y+h, x:x+w]
cv2.imwrite('image.png', image)
cv2.imwrite('ROI.png', ROI)
cv2.waitKey()
我是一名优秀的程序员,十分优秀!