开启左侧

PyCharm写的相机棋盘格标定程序

[复制链接]
Criss 发表于 2022-7-16 12:14:27 | 显示全部楼层 |阅读模式
  1. import numpy as np
  2. import yaml as yml
  3. import cv2

  4. RowCorner = 11
  5. ColCorner = 17
  6. GridX = 50
  7. GridY = 50

  8. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  9. img = cv2.imread("C:\\Users\\Criss\\Desktop\\Calib1.bmp")
  10. cv2.imshow('calib', img)
  11. cv2.waitKey(0)

  12. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  13. cv2.imshow('gray', gray)
  14. cv2.waitKey(0)

  15. ret,corners = cv2.findChessboardCorners(gray, (ColCorner, RowCorner), 1+2+8)
  16. cv2.waitKey(0)

  17. objp = np.zeros((ColCorner*RowCorner, 3), np.float32)
  18. objp[:, :2] = np.mgrid[0:ColCorner*GridX:GridX, 0:RowCorner*GridY:GridY].T.reshape(-1, 2)

  19. objpoints = []
  20. imgpoints = []
  21. if ret == True:
  22.     objpoints.append(objp)
  23.     corner2 = cv2.cornerSubPix(gray, corners, (11, 11),(-1, -1), criteria)
  24.     imgpoints.append(corner2)
  25.     cv2.drawChessboardCorners(img, (ColCorner, RowCorner), corner2, ret)
  26.     cv2.namedWindow('gray', cv2.WINDOW_NORMAL)
  27.     cv2.imshow('gray', img)
  28.     cv2.waitKey()

  29.     ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
  30.     cv2.waitKey()

  31.     img1 = cv2.imread("C:\\Users\\Criss\\Desktop\\Calib.bmp")
  32.     h,  w = img1.shape[:2]
  33.     newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
  34.     cv2.waitKey()

  35.     # 保存结果
  36.     calib = {'matx': mtx, 'dist': dist}
  37.     f = open(r'Calib.yaml', 'w')
  38.     print(yml.dump(calib, f))

  39.     # undistort
  40.     dst = cv2.undistort(img1, mtx, dist, None, newcameramtx)

  41.     # crop the image
  42.     x, y, w, h = roi
  43.     dst = dst[y:y+h, x:x+w]
  44.     cv2.imshow('undistort', dst)
  45.     cv2.waitKey()
  46.     cv2.imwrite('calibresult.png', dst)
复制代码

官方指导文档:https://docs.opencv.org/4.5.0/d4 ... ra_calibration.html

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表