我写了一个代码片段来检测交通标志的形状。该代码对于检测除三角形交通标志以外的形状相当有效。我尝试将值(即 0.01(调整为函数 cv2.approxPolyDP(c, 0.01 * peri, True( 的第二个参数,但我无法找到正确的值。
我尝试将值(即 0.01(调整为函数 cv2.approxPolyDP(c, 0.01 * peri, True( 的第二个参数,但我无法找到正确的值。
from os import listdir
from os.path import isfile, join
import cv2
myPath = '/home/raghu/Downloads/SSIMProject/ImageData/sample'
files = [ f for f in listdir(myPath) if isfile(join(myPath, f))]
for eachFile in files:
img = cv2.imread(join(myPath, eachFile), 1)
cv2.imshow('img1', img[:,:,0])
ret, thresh1 = cv2.threshold(img[:,:,0], 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours,hierarchy = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
font = cv2.FONT_HERSHEY_COMPLEX
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.0112 * cv2.arcLength(cnt, True), True)
print(len(approx))
if len(approx) == 8:
print("Octagon")
cv2.putText(img, 'Octagon', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
elif len(approx) == 7:
print("Heptagon")
cv2.putText(img, 'Heptagon', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
elif len(approx) == 6:
print("Hexagon")
cv2.putText(img, 'Hexagon', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
elif len(approx) == 5:
print("Pentagon")
cv2.putText(img, 'Pentagon', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
elif len(approx) == 4:
print("Square")
cv2.putText(img, 'Square', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
elif len(approx) == 3:
print("Triangle")
cv2.putText(img, 'Triangle', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
else:
print("Circle")
cv2.putText(img, 'Circle', (10, 30), font, 0.3, (0, 0, 0), 1, cv2.LINE_AA)
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
cv2.imshow('sign', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
我希望三角形的交通标志被检测到。
请尝试以下代码,它将帮助您检测图像中的三角形一旦您可以根据交通三角形(例如红色过滤器(的颜色创建一个颜色过滤器,然后使用它,以便它始终仅检测红色标志
import cv2
import numpy as np
font = cv2.FONT_HERSHEY_COMPLEX
img = cv2.imread("shapes.jpg", cv2.IMREAD_GRAYSCALE)
_, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
cv2.drawContours(img, [approx], 0, (0), 5)
x = approx.ravel()[0]
y = approx.ravel()[1]
cv2.putText(img, "Triangle", (x, y), font, 1, (0))
cv2.imshow("shapes", img)
cv2.imshow("Threshold", threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()