2024-09-28 03:18:35 发布
网友
有两种图像,一种是有价值的原始图像,另一种叫形状图像,形状不规则。我想检测形状,并向img值添加不同的值,对应于形状img。形状不会互相相交。 我已经浏览了多个lib,包括opencv2,但是发现很难实现这个目标。有人能帮忙吗?谢谢。你知道吗
可能形状图像
我希望从外到内交替添加+1/-1
要检测形状,可以使用^{}和cv2.RETR_TREE标志。为了确定内部轮廓,我们可以使用层次结构对每个内层进行过滤。这里有一个关于contour hierarchy的好教程。本质上,我们遍历每一层并交替标记每个轮廓(-1或1)。要添加标签,可以使用^{}。您可能需要根据所使用的图像更改标签的偏移量。你知道吗
cv2.RETR_TREE
-1
1
结果是这样的
import cv2 image = cv2.imread('1.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray,120, 255,cv2.THRESH_BINARY_INV)[1] cnts, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) label = '1' count = 0 # Get inner list of hierarchy for layer in zip(cnts, h[0]): contour = layer[0] hierarchy = layer[1] # If we find new contour (not inner) reset label if hierarchy[1] >= 0: label = '1' # Ensure that we only have outer contour if count % 2 == 0: cv2.drawContours(image, [contour], -1, (36, 255, 12), 2) x,y,w,h = cv2.boundingRect(contour) cv2.putText(image, label, (x +50,y+ 70), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 3) label = str(int(label) * -1) count += 1 cv2.imshow('thresh', thresh) cv2.imshow('image', image) cv2.waitKey()
要检测形状,可以使用^{} 和} 。您可能需要根据所使用的图像更改标签的偏移量。你知道吗
cv2.RETR_TREE
标志。为了确定内部轮廓,我们可以使用层次结构对每个内层进行过滤。这里有一个关于contour hierarchy的好教程。本质上,我们遍历每一层并交替标记每个轮廓(-1
或1
)。要添加标签,可以使用^{结果是这样的
相关问题 更多 >
编程相关推荐