2024-10-04 09:21:13 发布
网友
我的输入图像
提取高亮显示的部分
我想要的输出
请有人帮忙给我一个建议。我的照片是这样的。这只是一个样品。我需要裁剪底部模板部分,并做OCR。我已附上我的愿望输出图片。请看一下。如何使用python实现它?在
注:片材尺寸会有所不同,模板可能会错位。但主要是在左下角
以下是一种可能的方法:
获取二值图像。我们将其转换为灰度、高斯模糊,然后使用Otsu阈值
填充潜在轮廓。我们迭代轮廓并使用轮廓近似进行过滤,以确定它们是否为矩形。
执行形态学操作。我们使用矩形核对非矩形轮廓进行变形打开。
过滤并提取所需轮廓。找到轮廓并使用轮廓近似、纵横比和轮廓面积进行过滤,以隔离所需轮廓。然后用Numpy切片提取。
提取ROI
代码
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()
以下是一种可能的方法:
获取二值图像。我们将其转换为灰度、高斯模糊,然后使用Otsu阈值
填充潜在轮廓。我们迭代轮廓并使用轮廓近似进行过滤,以确定它们是否为矩形。
执行形态学操作。我们使用矩形核对非矩形轮廓进行变形打开。
过滤并提取所需轮廓。找到轮廓并使用轮廓近似、纵横比和轮廓面积进行过滤,以隔离所需轮廓。然后用Numpy切片提取。
提取ROI
代码
相关问题 更多 >
编程相关推荐