gpt4 book ai didi

python - 获取重复轮廓

转载 作者:行者123 更新时间:2023-12-02 18:06:32 26 4
gpt4 key购买 nike

我想提取每个图像中的轮廓/对象的数量及其侧面,即函数应返回[num_contours,total_sides,(单个轮廓的侧面)]

但是我为每个形状得到两个轮廓(外部和内部)。

Original image Contour 1 Contour 2 Contour 3 Contour 4

我的功能:

def get_contour_details(img):
image = img.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
value, thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contour_edges = [len(cv2.approxPolyDP(contour, 0.01* cv2.arcLength(contour, True), True)) for contour in contours]
num_contours = len(contours)
total_edges = sum(contour_edges)
return num_contours, total_edges, contour_edges

预期答案:[2, 8, [4,4]]

得到:[4, 18, [4, 4, 4, 6]]

使用下图进行处理:

enter image description here

任何形式的帮助将不胜感激!

最佳答案

Open cv 将识别并返回内部和外部轮廓。您需要根据您的需要过滤它们。轮廓之间的关系可以从层次结构中推断出来。层次结构返回以下列表,

[next, previous, first_child, parent]
# next and previous are with respect to same hierarchy level.

如果您对外部轮廓感兴趣,则没有父级 (parent = -1) 的行将显示外部轮廓。如果您需要内部轮廓,则父级将是一个非负数(表示父级在轮廓列表中的索引)。

以下代码(为了更简单,我使用“cv2.RETR_CCOMP”标志进行层次结构检索,因为它只提供了两级层次结构)将基于考虑外部轮廓来完成这项工作,并在示例图像上进行测试。

import numpy as np
import cv2

def get_contour_details(img):
image = img.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
value, thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
# Find external contours.
index = np.argwhere(hierarchy[0,:,3] == -1).flatten()
contours = [contours[i] for i in index]
#
contour_edges = [len(cv2.approxPolyDP(contour, 0.01* cv2.arcLength(contour, True), True)) for contour in contours]
num_contours = len(contours)
total_edges = sum(contour_edges)
return num_contours, total_edges, contour_edges

img = cv2.imread('img.png', cv2.IMREAD_COLOR)
print(get_contour_details(img))

要更好地了解轮廓层次及其不同类型,请参阅 Hierarchy explanation from opencv official tutorial .

关于python - 获取重复轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73145791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com