【发布时间】:2019-09-03 18:59:28
【问题描述】:
【问题讨论】:
标签: python image opencv image-processing computer-vision
【问题讨论】:
标签: python image opencv image-processing computer-vision
这是一个简单的方法:
转换为灰度后,我们阈值得到二值图像
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)[1]
接下来我们创建一个内核并执行morphological operations 来平滑图像。这一步通过侵蚀图像“破坏”连接三个矩形的关节
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,25))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)
从这里我们找到轮廓并使用 numpy 切片提取 ROI。在原始图像上绘制所需矩形的边界框
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
image_number = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
ROI = original[y:y+h, x:x+w]
cv2.imwrite("ROI_{}.png".format(image_number), ROI)
image_number += 1
这是每个人保存的投资回报率
完整代码
import cv2
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,25))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
image_number = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
ROI = original[y:y+h, x:x+w]
cv2.imwrite("ROI_{}.png".format(image_number), ROI)
image_number += 1
cv2.imshow('opening', opening)
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
【讨论】:
这看起来像 opening 的情况,其内核足够大,可以侵蚀矩形之间的线。
另一种方法是多次调用erode,然后调用相同次数的dilate。
一个小建议,您可能需要对图像应用阈值保持,因为看起来您有一些噪点(尤其是在左侧和顶部的矩形上)。
【讨论】: