我需要计算长轴长度、短轴长度和偏心率。我正在使用 fitEllipse() 进行计算。但是某些对象的长轴长度给出的值高于高度值。我找不到如何解决这个问题。
这是代码:
import cv2
import numpy as np
img = cv2.imread('Resources/son1.png')
#input and output image
def getContours(img,imgContour):
#Find contours and set contour retrivial mode
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#cnt is the one of the contours for every object in image
for cnt in contours:
# Contour for shape and I find area and length using this contour
cv2.drawContours(imgContour, cnt,-1, (0, 255, 0), 1)
BoundingBox(Rectangle):给出边界框参数 => (x,y,width,height)
x, y, w, h = cv2.boundingRect(cnt)
img = cv2.rectangle(imgContour,(x, y),(x+w, y+h),(0,255,0),2)
print("bounding_box(x,y,w,h):", x, y, w, h)
#W: and H: texts (Length)
cv2.putText(imgContour, "w={},h={}".format(w,h), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0),1,16)
# give us specific contour (cnt) area
area = cv2.contourArea(cnt)
# Area text
cv2.putText(imgContour, "Area: " + str(int(area)), (x + w + 20, y + 45), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(255, 0, 0), 1, 16)
# # #Center of objects in picture
#
# M = cv2.moments(cnt)
# print(M)
# centx = int(M['m10'] / M['m00'])
# centy = int(M['m01'] / M['m00'])
#
# print(centx,centy)
长轴长度、短轴长度、偏心率
(x,y), (minorAxisLength, majorAxisLength), angle = cv2.fitEllipse(cnt)
ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img,ellipse,(0, 0, 255), 2)
#semi-major and semi-minor
a = majorAxisLength / 2
b = minorAxisLength / 2
#Formula of eccentricity is :
Eccentricity = round(np.sqrt(pow(a, 2) - pow(b, 2))/a, 2)
x = int(x + w / 2) + 1
y = int(y + h / 2) + 1
cv2.putText(imgContour, 'Minor ='+str(round(minorAxisLength, 2)), (x+10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1,16)
cv2.putText(imgContour, 'Major ='+str(round(majorAxisLength, 2)), (x+10, y+20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1, 16)
cv2.putText(imgContour, 'Eccentricity ='+str(round(Eccentricity, 3)), (x+10, y+40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1, 16)
imgContour = img.copy()
imgBlur = cv2.GaussianBlur(img, (7, 7),1)
imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
ImgThresh = cv2.threshold(imgGray, 100 , 255, cv2.THRESH_BINARY)[1]
imgCanny = cv2.Canny(imgGray,50,50)
getContours(imgCanny,imgContour)
cv2.imshow("Original Image", img)
cv2.imshow("Canny", imgCanny)
cv2.imshow("Contour", imgContour)
cv2.waitKey(0)
cv2.destroyAllWindows()