OpenCV 是一个强大的图像处理工具。
我试图为你的问题想出一个解决方案,但我不知道这个解决方案在 900 张图像中的稳定性如何。特别是,0° - 180° 轴不得明显倾斜,因为我没有对此进行校正。
import cv2 as cv
import numpy as np
#load image
img = cv.imread(r'C:\Users\dekarcch\Desktop\zvnZM.jpg', cv.IMREAD_GRAYSCALE)
#detect circle
circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 100,
param1=100, param2=30,
minRadius=50, maxRadius=500)
# get circle center (raise Exception if circle was not detected)
try:
center = (int(circles[0,0,0]), int(circles[0,0,1]))
except IndexError:
raise Exception("Unable to identify center.")
# plot center of circle
cv.circle(img, center, 1, (0, 100, 100), 3)
# dilate and threshold image to only see the rectangle as small dot
kernel = np.ones((35, 35), np.uint8)
img_dilate = cv.dilate(img, kernel, iterations=1)
_, img_dilate_thres = cv.threshold(img_dilate,120,255,cv.THRESH_BINARY)
# get center position of remaining dot
rect_x = np.argmin(img_dilate_thres.mean(axis=0))
rect_y = np.argmin(img_dilate_thres.mean(axis=1))
cv.circle(img, (rect_x, rect_y), 1, (0, 100, 100), 3)
# get angle between circle center and patch
angle = np.arctan2(center[1] - rect_y, rect_x - center[0])
degree = angle / (2*np.pi) * 360
# display angle, wait for user to close image
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img, f'{degree:.1f}', (rect_x, rect_y), font, 2, (0, 255, 0), 2, cv.LINE_AA)
cv.imshow("detected circles", img)
cv.waitKey(0)