import cv2 as cv
import numpy as np
import os
def detect_circular_image(image_path, out_path):
# 读取文件
origin = cv.imread(image_path, 1)
img = cv.imread(image_path, 0)
# 获取图片中心点
(h, w) = img.shape[:2]
center_x, center_y = w / 2, h / 2
# 霍夫圆检测
circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 100, param1=50, param2=80, minRadius=30, maxRadius=40)
circles = np.uint16(np.around(circles))
# 将检测到的圆圈标上去
for i in circles[0, :]: # 遍历矩阵每一行的数据
cv.circle(origin, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv.circle(origin, (i[0], i[1]), 2, (0, 0, 255), 3)
cv.putText(origin, "({},{})".format((i[0] - center_x) / 100,
(-(i[1] - center_y) if (i[1] > center_y) else center_y - i[1]) / 100),
(i[0] - 10, i[1] - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, (242,74,65), 2)
# 显示图像
cv.imwrite(out_path, origin)
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == '__main__':
for root, dirs, files in os.walk("F:\\images\\ningluosi"):
for file in files:
if file.endswith('.jpg') or file.endswith('.png'): # 根据需要调整文件扩展名过滤条件
image_path = os.path.join(root, file)
detect_circular_image(image_path,"F:\\images\\ningluosi\\ceshi\\"+file) # 检测圆形图片的坐标
cv.HoughCircles 中的 param2值越大,检测到的文件可能丢失,值小的时候,可能会获取到其他图形
minRadius:圆的最小半径
maxRadius: 最大半径
我上述坐标中获取的是unity中的坐标,直接粗暴的/100,实际中可以不除