遇到问题一直是github,csdn,stackoverflow三个网站找解决方法,跟大佬学习了很多。最近学习CV时遇到图片的Rectification问题,一直不知道如何解决,网上也没有前辈分享过经验,今天终于解决了这个问题,于是想记录一下,由于时间比较晚了,先放代码,日后再来更新具体思路。

##Created by Caining Liu
##11:19PM March 3, 2020import cv2
import glob
import os
import numpy as np
from matplotlib import pyplot as plt nb_vertical = 9
nb_horizontal = 6
#termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,30,0.001)
#prepare object points, like(0 0 0),(1 0 0),(2 0 0) ,etc
objp = np.zeros((nb_horizontal*nb_vertical,3),np.float32)
objp[:,:2] = np.mgrid[0:nb_vertical,0:nb_horizontal].T.reshape(-1,2)#Arrays to store object points and image points from all the images.
objpoints = []
imgpoints = []#prepare object points, like(0 0 0),(1 0 0),(2 0 0) ,etc
objp_r = np.zeros((nb_horizontal*nb_vertical,3),np.float32)
objp_r[:,:2] = np.mgrid[0:nb_vertical,0:nb_horizontal].T.reshape(-1,2)#Arrays to store object points and image points from all the images.
objpoints_r = []
imgpoints_r = []def calibrate_each_camera(path,objpoints,imgpoints):
images = sorted(glob.glob(path))
print(len(images))
assert images
gray_list = []
for fname in images:img = cv2.imread(fname)gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)gray_list.append(gray)#Implement findChessboardCorners
ret, corners = cv2.findChessboardCorners(gray,(nb_vertical,nb_horizontal),None)
#If found, add object points, image points
if ret == True:objpoints.append(objp)imgpoints.append(corners)ret,mtx,dist,rvecs,tvecs = cv2.calibrateCamera(objpoints,imgpoints,gray.shape[::-1],None,None)
return mtx,dist,rvecs,tvecsdef undistort(images,mtx,dist):raw_images = []undst_set = []for fname in images:img = cv2.imread(fname)h,w = img.shape[:2]newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))undst = cv2.undistort(img,mtx,dist,None,newcameramtx)x,y,w,h = roiundst = undst[y:y+h, x:x+w]undst_set.append(undst)return undst_setif __name__ == "__main__":path1 = 'left/*.png'mtx_l,dist_l,rvecs_l,tvecs_l = calibrate_each_camera(path1,objpoints,imgpoints)path2 = 'right/*.png'mtx_r,dist_r,rvecs_r,tvecs_r = calibrate_each_camera(path2,objpoints_r,imgpoints_r)images_l = sorted(glob.glob('left/*.png'))print(len(images_l))assert images_limages_r = sorted(glob.glob('right/*.png'))print(len(images_r))assert images_rif not os.path.exists('undistort_left'):os.makedirs('undistort_left')if not os.path.exists('undistort_right'):os.makedirs('undistort_right')undistort_img_left = undistort(images_l,mtx_l,dist_l)undistort_img_right = undistort(images_r,mtx_r,dist_r)for i in range(len(undistort_img_left)):cv2.imwrite('undistort_left/'+str(i)+".png",undistort_img_left[i])for j in range(len(undistort_img_right)):cv2.imwrite('undistort_right/'+str(j)+".png",undistort_img_right[j])#Get the relative pose between the two cameras(R T)stereocalibration_criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS,100,1e-5)stereocalibration_retval,newcameramtx_left,dist_left,newcameramtx_right,dist_right,R,T,E,F = cv2.stereoCalibrate(objpoints,imgpoints,imgpoints_r,mtx_l,dist_l,mtx_r,dist_r,undistort_img_left[0].shape[0:2][::-1],criteria=stereocalibration_criteria,flags=cv2.CALIB_FIX_INTRINSIC)#calculate rotation matrix for each camera that make l/r camera image planes equalR1, R2, P1, P2 = cv2.stereoRectify(cameraMatrix1=newcameramtx_left,cameraMatrix2=newcameramtx_right,distCoeffs1=dist_left,distCoeffs2=dist_right,imageSize=undistort_img_left[0].shape[0:2][::-1],R=R,T=T,Q=None,flags=cv2.CALIB_ZERO_DISPARITY,newImageSize=(0,0))[0:4]#compute stereo rectification mapsmap1x, map1y = cv2.initUndistortRectifyMap(newcameramtx_left,dist_left,R1,P1,undistort_img_left[0].shape[0:2][::-1],cv2.CV_32FC1)map2x, map2y = cv2.initUndistortRectifyMap(newcameramtx_right,dist_right,R2,P2,undistort_img_left[0].shape[0:2][::-1],cv2.CV_32FC1)#output the rectified images and save themif not os.path.exists('rectified_left'):os.makedirs('rectified_left')if not os.path.exists('rectified_right'):os.makedirs('rectified_right')for i in range(len(undistort_img_left)):rec = cv2.remap(undistort_img_left[i],map1x,map1y,cv2.INTER_LINEAR)cv2.imwrite('rectified_left/'+str(i)+".png",rec)for j in range(len(undistort_img_right)):rec = cv2.remap(undistort_img_right[j],map2x,map2y,cv2.INTER_LINEAR)cv2.imwrite('rectified_right/'+str(j)+".png",rec)

Undistort and Rectify Images based on OpenCV(python)相关推荐

  1. 【ZED】从零开始使用ZED相机(五):Opencv+Python实现相机标定(双目)

    引言 同样Opencv+Python实现双目相机的标定,单目标定详见[ZED]从零开始使用ZED相机(五):Opencv+Python实现相机标定(单目) 1 cv2.stereoCalibrate ...

  2. OpenCV+python:Canny边缘检测算法

    1,边缘处理 图像边缘信息主要集中在高频段,通常说图像锐化或检测边缘,实质就是高频滤波.我们知道微分运算是求信号的变化率,具有加强高频分量的作用. 在空域运算中来说,对图像的锐化就是计算微分.由于数字 ...

  3. OpenCV Python在计算机视觉中的应用

    OpenCV Python教程 在这篇文章中,我们将使用Python中的OpenCv来涵盖计算机视觉的各个方面.OpenCV长期以来一直是软件开发的重要组成部分. 什么是计算机视觉? 我们考虑一个场景 ...

  4. OpenCV Python教程(2、图像元素的访问、通道分离与合并)

    OpenCV Python教程之图像元素的访问.通道分离与合并 转载请详细注明原作者及出处,谢谢! 访问像素 像素的访问和访问numpy中ndarray的方法完全一样,灰度图为: [python] v ...

  5. python中import cv2遇到的错误及安装方法_独家利用OpenCV,Python和Ubidots来构建行人计数器程序(附代码amp;解析)...

    作者:Jose Garcia 翻译:吴振东 校对:张一豪 本文约4000字,建议阅读14分钟. 本文将利用OpenCV,Python和Ubidots来编写一个行人计数器程序,并对代码进行了较为详细的讲 ...

  6. 如何把OpenCV Python获取的图像传递到C层处理

    原文:https://blog.csdn.net/yushulx/article/details/52788051 用OpenCV Python来开发,如果想要用到一些C/C++的图像处理库,就需要创 ...

  7. openCV—Python(6)—— 图像算数与逻辑运算

    openCV-Python(6)-- 图像算数与逻辑运算 一.函数简介 1.add-图像矩阵相加 函数原型:add(src1, src2, dst=None, mask=None, dtype=Non ...

  8. opencv python 图像去噪

    opencv python 图像去噪 文章目录: https://blog.csdn.net/Annihilation7/article/details/82718470 https://segmen ...

  9. opencv python 中cv2.putText()函数的用法

    opencv python 中cv2.putText()函数的用法 文章目录: 一.快速使用 二.官方文档 三.使用举例 虽然用啦很多次,还是决定记录一下 一.快速使用 cv2.putText(ima ...

最新文章

  1. mysql 主从复制 position_mysql 主从复制原理及步骤。
  2. BP神经网络-- C语言实现
  3. 【揭秘】视频直播关键技术
  4. 【渝粤题库】陕西师范大学165202 战略管理 作业(专升本)
  5. plupload怎么设置属性_腾达无线路由器怎么设置,这些是你要知道的
  6. 如何把本地yum源给其他机器使用_配置本地yum源以及第3方软件仓库的搭建
  7. ktv管理系统_7天撸完KTV点歌系统,含后台管理系统(完整版)
  8. JSP servlet的配置与使用
  9. 通向从容之道——Getting things done读书笔记
  10. mysql脱库_mysql 脱裤(脱库)通用脚本
  11. python井字棋_用python井字棋
  12. Linux桌面没有minidwep,ubuntu 12.04完整安装minidwep-gtk教程
  13. 周末鸡汤|电子游戏教给你的人生一课 from Quora
  14. python 关于sys.argv[1]语句报错IndexError: list index out of range的解决
  15. 普通的dub的sdl配置
  16. prisma2.0和nexus搭建graphql后端(1)—prisma2.0
  17. DSP28335软件实验研究--DA_AD模块功能详解
  18. html大风效果,使用jquery.windy制作风吹卡片的效果 | jQuery教程
  19. Docker - Docker Container及Container命令详解
  20. Encountered end of file

热门文章

  1. 老司机写的java代码_老司机告诉你高质量的Java代码是怎么练成的?
  2. Codeforces Round #428 (Div. 2):A. Arya and Bran
  3. 推荐算法——NCF知识总结代码实现
  4. 《中级数据库系统工程师》
  5. 《Java 2 实用教程》课程学习(17)——《Java 程序设计》实验指导书-校内实验教材
  6. 牛顿3种方法解重根情形对比
  7. ubuntu22.04装机中基本软件
  8. node.js+uniapp计算机毕业设计安卓移动LYQ电子商城APP(程序+APP+LW)
  9. 30个漂亮的免费 Flash 网站模板下载
  10. php cookie 加密解密,php 使用base64加密、解密cookie的示例