python opencv 相机标定 畸变矫正 霍夫圆检测识别圆形
时间: 2023-09-30 09:12:38 浏览: 279
好的,下面我给您讲解一下:
1. 相机标定:通过拍摄不同姿态的标定板,使用OpenCV中的calibrateCamera函数来计算相机的内参矩阵和畸变参数,从而实现相机标定。
2. 畸变矫正:通过相机标定得到的内参矩阵和畸变参数,使用OpenCV中的undistort函数来对图像进行畸变矫正,从而得到更加准确的图像。
3. 霍夫圆检测:使用OpenCV中的HoughCircles函数进行霍夫圆检测,该函数会返回检测到的圆形的圆心坐标和半径。
具体实现过程可以参考以下代码:
```python
import cv2
import numpy as np
# 相机标定
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((6*7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)
objpoints = []
imgpoints = []
images = glob.glob('calib/*.png')
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
img = cv2.drawChessboardCorners(img, (7, 6), corners2, ret)
cv2.imshow('img', img)
cv2.waitKey(500)
cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
# 畸变矫正
img = cv2.imread('test.png')
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
# 霍夫圆检测
gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1, minDist=100, param1=50, param2=30, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
cv2.circle(dst, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv2.circle(dst, (i[0], i[1]), 2, (0, 0, 255), 3)
cv2.imshow('result', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码中,calib文件夹中存放的是标定板的图片,test.png是待检测的圆形图片。运行代码后,会弹出标定板图片,需要手动选择标定板的角点,然后程序会自动计算相机内参矩阵和畸变参数。接着会输出畸变矫正后的图片,并在图片中检测圆形并标记出来。
阅读全文