我的代码有问题,它应该得到两行输入,第一行是图像中有多少个形状,第二行是图像路径。
输出应该是形状类型的数量,例如输入:有一个test1.jpg
图像,其中有10个圆圈,输出应该是:1
我的代码写在这里:
import cv2
import numpy as np
num_shapes = int(input("Enter the number of shapes in the image: "))
image_path = input("Enter the path to the image: ")
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 100]
num_detected_shapes = len(filtered_contours)
print("Detected shapes:", num_detected_shapes)
字符串
但对于这张图片:
的数据
它给出的输出是1。
为什麽?
1条答案
按热度按时间cgvd09ve1#
您的图像对比度非常差,背景值非常高。强调背景和形状之间差异的一种方法是使用大津阈值而不是二进制:
字符串
之后,您需要反转二进制掩码,因为在您的情况下,最高值是背景而不是形状。
型
之后,最好通过检查和阈值化来引入一些对比:
型
这也是轮廓的图像:
的数据
V2.0:增加形状计数
要识别轮廓的类型,您可以使用
cv2.approxPolyDP
来近似形状。这个想法是在之后计算顶点:型
之后,这里是总结:
型
这将给予以下内容:
型
的