标定针孔相机的代码为:

import cv2
import numpy as np
import glob# 设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001
criteria = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 30, 0.001)# 获取标定板角点的位置
objp = np.zeros((4 * 7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:4].T.reshape(-1, 2)  # 将世界坐标系建在标定板上,所有点的Z坐标全部为0,所以只需要赋值x和yobj_points = []  # 存储3D点
img_points = []  # 存储2D点
images = glob.glob("F:\\adataset\\calibration\\pinhole\\bag1_300\\*.jpg")
#images = glob.glob("C:/Users/lenovo/Desktop/fishcali/last/8828/*.png")
#images = glob.glob("C:/Users/lenovo/Desktop/fishcali/calipictures/new8828-25/*.png")
i=0;
for fname in images:#print("a")img = cv2.imread(fname)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)size = gray.shape[::-1]ret, corners = cv2.findChessboardCorners(gray, (7, 4), None)#print(corners)if ret:obj_points.append(objp)corners2 = cv2.cornerSubPix(gray, corners, (5, 5), (-1, -1), criteria)  # 在原角点的基础上寻找亚像素角点#print(corners2)if [corners2]:img_points.append(corners2)else:img_points.append(corners)cv2.drawChessboardCorners(img, (7, 4), corners, ret)  # 记住,OpenCV的绘制函数一般无返回值i+=1;cv2.imwrite('./pyresults/conimg'+str(i)+'.png', img)cv2.waitKey(1500)else:print(str(fname))print(len(img_points))
cv2.destroyAllWindows()# 标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, size, None, None)print("ret:", ret)
print("内参矩阵mtx:\n", mtx) # 内参数矩阵
print("畸变系数dist:\n", dist)  # 畸变系数   distortion cofficients = (k_1,k_2,p_1,p_2,k_3)
print("旋转向量rvecs:\n", rvecs)  # 旋转向量  # 外参数
print("平移向量tvecs:\n", tvecs ) # 平移向量  # 外参数print("-----------------------------------------------------")img = cv2.imread(images[2])
h, w = img.shape[:2]
print("调节视场大小后的相机内参为:\n")
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))#显示更大范围的图片(正常重映射之后会删掉一部分图像)
print (newcameramtx)
print("------------------使用undistort函数-------------------")
dst = cv2.undistort(img,mtx,dist,None,newcameramtx)
x,y,w,h = roi
dst1 = dst[y:y+h,x:x+w]
cv2.imwrite('./pyresults/calibresult3.png', dst1)
cv2.imshow("original", img)
cv2.imshow("undistorted", dst1)
print ("dst的大小为:", dst1.shape)
cv2.waitKey(0)
cv2.destroyAllWindows()

标定鱼目相机的代码为:

# -*- coding: utf-8 -*-import yaml
import cv2
import numpy as np
import globCHECKERBOARD = (4, 7)
subpix_criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC + cv2.fisheye.CALIB_CHECK_COND + cv2.fisheye.CALIB_FIX_SKEW
objp = np.zeros((1, CHECKERBOARD[0] * CHECKERBOARD[1], 3), np.float32)
objp[0, :, :2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
_img_shape = None
objpoints = []  # 3d point in real world space
imgpoints = []  # 2d points in image plane.
#images = glob.glob('C:/Users/lenovo/Desktop/fishcali/last/8827/*.jpg')
images = glob.glob('D:\\adataset\\calibration\\newfisheye\\8830\\midleft1/*.jpg')for fname in images:img = cv2.imread(fname)if _img_shape == None:_img_shape = img.shape[:2]else:assert _img_shape == img.shape[:2], "All images must share the same size."gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# Chess board cornersret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD,cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE)# Image points (after refinin them)if ret == True:objpoints.append(objp)cv2.cornerSubPix(gray, corners, (3, 3), (-1, -1), subpix_criteria)imgpoints.append(corners)
N_OK = len(objpoints)
K = np.zeros((3, 3))
D = np.zeros((4, 1))
rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
rms, _, _, _, _ = \cv2.fisheye.calibrate(objpoints,imgpoints,gray.shape[::-1],K,D,rvecs,tvecs,calibration_flags,(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6))
print("Found " + str(N_OK) + " valid images for calibration")
print("DIM=" + str(_img_shape[::-1]))
print("K=np.array(" + str(K.tolist()) + ")")
print("D=np.array(" + str(D.tolist()) + ")")
DIM = _img_shape[::-1]
balance = 1
dim2 = None
dim3 = Noneimg = cv2.imread(images[0])
dim1 = img.shape[:2][::-1]  # dim1 is the dimension of input image to un-distort
assert dim1[0] / dim1[1] == DIM[0] / DIM[1], "Image to undistort needs to have same aspect ratio as the ones used in calibration"
if not dim2:dim2 = dim1
if not dim3:dim3 = dim1
scaled_K = K * dim1[0] / DIM[0]  # The values of K is to scale with image dimension.
scaled_K[2][2] = 1.0  # Except that K[2][2] is always 1.0
# This is how scaled_K, dim2 and balance are used to determine the final K used to un-distort image. OpenCV document failed to make this clear!
new_K = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(scaled_K, D, dim2, np.eye(3), balance=balance)#newK 是去畸变后的K
map1, map2 = cv2.fisheye.initUndistortRectifyMap(scaled_K, D, np.eye(3), new_K, dim3, cv2.CV_16SC2)
undistorted_img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)data = {'dim1': dim1,'dim2': dim2,'dim3': dim3,'K': np.asarray(K).tolist(),'D': np.asarray(D).tolist(),'new_K': np.asarray(new_K).tolist(),'scaled_K': np.asarray(scaled_K).tolist(),'balance': balance}import jsonwith open("kannala_8828.json", "w") as f:json.dump(data, f)cv2.imshow("undistorted", undistorted_img)
img2 = cv2.imread(images[0])
cv2.imshow("none undistorted", img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

python-opencv标定相机内参(针孔+鱼目)相关推荐

  1. Python+OpenCv 标定相机参数的实现

    文章目录 一.制作标定板 二.提取标定板的世界坐标 三.张正友标定相机 (一)原理描述 (二)相机内参数 (三)单应矩阵 (四)内参约束条件 (五)求解内参数 (六)最大似然估计 (七)消除径向畸变 ...

  2. matlab标定相机内参

    一.获取单目针孔相机数据 在APP中选择Camera Calibrator,如下: 点击 Add Images,导入拍照图片.标定20张左右就够了,然后角度变一下,但不需要变太大,太大了会影响标定效果 ...

  3. halcon使用直线标定板,标定相机内参代码

    read_image (Image, '直线标定板图片/Left201118140641772.bmp') get_image_size (Image, Width, Height) dev_clos ...

  4. Python OpenCV实践,相机标定

    Python OpenCV实践,相机标定 前言 准备棋盘格 标定相机 图像去畸变 前言 本篇主要是使用python opencv标定相机内参和畸变参数的记录,主要参考opencv官方文档中的示例. 本 ...

  5. opencv+pythons相机标定源码解析

    相机标定原理,这里不再赘述,一般使用张友正相机标定法.这里只介绍了标定相机内参的方法,即3x3的matrix. import cv2 import numpy as np import glob# 设 ...

  6. python控制相机,在OpenCV / Python中设置相机参数

    我正在使用来自Thorlabs(DC1545M)的USB摄像机的OpenCV(2.4)和Python(2.7.3). 我正在对视频流进行一些图像分析,我希望能够从我的视频流中更改某些相机参数.令人困惑 ...

  7. livox_camera_lidar_calibration学习--相机内参标定

    开源代码位于:GitHub - Shelfcol/livox_camera_lidar_calibration_modified: livox_camera_lidar_calibration的改进得 ...

  8. 小觅相机的相机标定全家桶(相机IMU,相机内参,相机外参)

    性感帅哥博主在线标定小觅双目相机!!!(亲测有效系列!) 刚刚入手新小觅相机,结果飘出天际,很让人头疼!所以- 话不多说,开始骚操作! mkdir mynt_ws #创建文件夹 cd ~/mynt_w ...

  9. python opencv 调用摄像头失败问题的解决 Windows

    省流: 内含 Python Opencv 双目相机拍照代码(手动 or 自动),可自取: 如果你的 cv2.VideoCapture() 函数卡住但不报错,打开 Windows "相机&qu ...

  10. Python OpenCV相机参数详解:实现准确的相机标定和图像处理

    Python OpenCV相机参数详解:实现准确的相机标定和图像处理 在计算机视觉领域,相机参数是非常重要的元素.通过相机参数的标定,可以将图像中的像素坐标转化为真实世界中的坐标,从而实现准确的图像处 ...

最新文章

  1. 20100707 学习记录:[System.Web.Script.Services.ScriptService]引用问题
  2. linux去掉java路径_Java显示目录文件列表和删除目录
  3. Ubuntu报错记录(Could not get lock /var/lib/dpkg/lock-frontend问题的解决方法)
  4. deepin-安装问题:unable to find a medium containing a live file
  5. linux下别名alias的设置
  6. oracle中如何测试,Oracle数据库中如何正确的查看sql
  7. Atitit 代码的艺术 attilax 艾提拉著作 1. 代码就像一首歌,一个文章,一个绘画 1 2. 代码就像文章 2 2.1. ,要流畅读出来,使用dsl 方法连模式 2 2.2. 段落划分与
  8. mysql sql语句 参数化_MySQL存储过程准备语句(动态SQL)参数化
  9. 小米php架构图,小米首页布局框架
  10. SpringBoot房屋租赁系统
  11. android控制wifi,基于 Android 手机操作和控制的 Wifi 小车程序设计
  12. NetApp存储设置时间报“date: cannot set date when NTP is running.”处理
  13. 苹果电脑教程之退出ID账号
  14. perl Data::Dumper和Storable的例子
  15. Python输入关键词批量得到电商商品信息
  16. 以逗号为分隔符对字符串进行分隔
  17. 如何删除设备和驱动器中的百度网盘
  18. 易协软件:workflow与BPM区别
  19. excel数字后边添加单位
  20. linux内核模块编程(六)----字符设备驱动中断开发

热门文章

  1. proto_path passed empty directory name. (Use “.“ for current directory.)
  2. SRTF最短剩余时间优先调度C语言实现
  3. vue实战 —— 图书商城移动端项目
  4. 由偷菜/抢车位引发的思考
  5. 活着就是要做有意义的事,做有意义的事就是好好活着
  6. 支付宝APP支付扫码支付
  7. 电子科大杨宁TCPIP协议原理(总结)
  8. 小程序获取收货地址流程
  9. adb 配置自动获取时间 使用GPS提供的时间 使用网络提供的时间
  10. vue 统计中英文字符串长度_Ant Design Vue实现区分中英文分全角/半角字符长度校验功能...