【发布时间】:2020-03-07 18:33:41
【问题描述】:
我正在尝试在图像上绘制多个轮廓,到目前为止,我已经设法通过应用不同的阈值来绘制轮廓。唯一的问题是大多数轮廓区域是重叠的,我被困在这里如何处理它。我理想情况下想要的是,只要有重叠,它就应该将轮廓分成单独的区域。例如,在Conceptual image 中有 4 个区域(轮廓)橙色、绿色、蓝色和黑色。每当有重叠时,它应该分成紫色区域。这似乎很棘手,我什至不确定这是否可能。如果没有,我希望所有重叠合并。任何人都可以帮助解决这个问题吗? Sample image
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
im = cv.imread('images/sample.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret1, thresh1 = cv.threshold(imgray, 30, 80, 0)
ret2, thresh2 = cv.threshold(imgray, 80, 110, 0)
ret3, thresh3 = cv.threshold(imgray, 110, 150, 0)
ret4, thresh4 = cv.threshold(imgray, 150, 200, 0)
ret5, thresh5 = cv.threshold(imgray, 200, 255, 0)
_,contours1, hierarchy1 = cv.findContours(thresh1, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
_,contours2, hierarchy2 = cv2.findContours(thresh2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
_,contours3, hierarchy3 = cv2.findContours(thresh3,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
_,contours4, hierarchy4 = cv2.findContours(thresh4,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
_,contours5, hierarchy5 = cv2.findContours(thresh5,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im, contours1, -1, (0, 0, 255), 1)
cv2.drawContours(im, contours2, -1, (0, 255, 0), 1)
cv2.drawContours(im, contours3, -1, (0, 0, 255), 1)
cv2.drawContours(im, contours4, -1, (10, 200, 200), 1)
cv2.drawContours(im, contours5, -1, (255, 255, 0), 1)
cv2.imshow("im",im)
cv2.waitKey(0)
【问题讨论】:
-
这是您的实际输入图像,还是只是一些可视化?如果是后者,请发布实际的输入图像。一种昂贵的方法是在单独的蒙版上绘制填充的轮廓,并为每两个轮廓计算交点并找到它的轮廓。正如我所说,这会很昂贵,但我认为会给出准确的结果。
-
@HansHirse 这只是一个概念图像,用于理解问题。我已附上示例图片。
-
@HansHirse 如果我们说 10 个重叠的轮廓,那么找到这些区域需要大量的计算时间。还有其他方法吗?
-
不一定。我想,这种方法会占用大量内存,但计算量不会那么大,因为单个操作非常基础。
标签: python numpy opencv image-processing contour