喏,
为了解决您的问题,我会使用这个 sn-p 检测轮廓并在其区域上过滤它们,只留下大于给定大小的轮廓。在你的情况下,我假设你只是在搜索一个对象,但我准备好将代码扩展到具有多个对象的图片
import cv2
import numpy as np
# input image
path = "16.jpg"
# finding contours
def getContours(img, imgContour):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
finalContours = []
# for each contour found
for cnt in contours:
# find its area in pixel^2
area = cv2.contourArea(cnt)
print("Contour area: ", area)
# fixed assuming you are searching for the biggest object
# value can be found via previous print
minArea = 18000
if (area > minArea):
perimeter = cv2.arcLength(cnt, False)
# smaller epsilon -> more vertices detected [= more precision]
# improving bounding box precision - original value 0.02 * perimeter
epsilon = 0.002*perimeter
# check how many vertices
approx = cv2.approxPolyDP(cnt, epsilon, True)
print(len(approx))
finalContours.append([len(approx), area, approx, cnt])
# leaving this part if you have more objects to detect
# not needed when minArea has been chosen to detect only one object
# sorting the final results in descending order depending on the area
finalContours = sorted(finalContours, key = lambda x:x[1], reverse=True)
print("Final Contours number: ", len(finalContours))
for con in finalContours:
cv2.drawContours(imgContour, con[3], -1, (0, 0, 255), 3)
return imgContour, finalContours
# sourcing the input image
img = cv2.imread(path)
# img.shape gives back height, width, color in this order
original_height, original_width, color = img.shape
print('Original Dimensions : ', original_width, original_height)
# resizing to see the entire image
scale_percent = 30
width = int(original_width * scale_percent / 100)
height = int(original_height * scale_percent / 100)
print('Resized Dimensions : ', width, height)
dim = (width, height)
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Starting image", resized)
cv2.waitKey()
# blurring
imgBlur = cv2.GaussianBlur(resized, (7, 7), 1)
# graying
imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
# inizialing thresholds
threshold1 = 14
threshold2 = 17
# canny
imgCanny = cv2.Canny(imgGray, threshold1, threshold2)
# showing the last produced result
cv2.imshow("Canny", imgCanny)
cv2.waitKey()
kernel = np.ones((2, 2))
imgDil = cv2.dilate(imgCanny, kernel, iterations = 3)
imgThre = cv2.erode(imgDil, kernel, iterations = 3)
imgFinalContours, finalContours = getContours(imgThre, resized)
# show the contours on the unfiltered resized image
cv2.imshow("Final Contours", imgFinalContours)
cv2.waitKey()
cv2.destroyAllWindows()
使用所选值运行此程序的最终输出如下:
祝你有美好的一天,
安东尼诺