本文整理匯總了Python中cv2.undistort方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.undistort方法的具體用法?Python cv2.undistort怎麽用?Python cv2.undistort使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.undistort方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def test():
"""
read the pickle file on disk and implement undistor on image
show the oringal/undistort image
"""
print("Reading the pickle file...")
pickle_file = open("./camera_cal.p", "rb")
dist_pickle = pickle.load(pickle_file)
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
pickle_file.close()
print("Reading the sample image...")
img = cv2.imread('corners_founded/corners_found13.jpg')
img_size = (img.shape[1],img.shape[0])
dst = cv2.undistort(img, mtx, dist, None, mtx)
# dst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
# Visualize undistortion
print("Visulize the result...")
f, (ax1,ax2) = plt.subplots(1,2, figsize=(20,10))
ax1.imshow(img), ax1.set_title('Original Image', fontsize=15)
ax2.imshow(dst), ax2.set_title('Undistored Image', fontsize=15)
plt.show()
示例2: live_undistort
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def live_undistort(camera, camera_matrix, distortion_coefficients):
""" Using a given calibration matrix, display the distorted, undistorted, and cropped frame"""
scaled_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(
camera_matrix, distortion_coefficients, camera.size, 1, camera.size
)
while True:
ret, frame = camera.cap.read()
assert ret
distorted_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
undistorted_frame = cv2.undistort(
distorted_frame, camera_matrix, distortion_coefficients, None, scaled_camera_matrix,
)
roi_x, roi_y, roi_w, roi_h = roi
cropped_frame = undistorted_frame[roi_y : roi_y + roi_h, roi_x : roi_x + roi_w]
cv2.imshow("distorted %s" % (distorted_frame.shape,), distorted_frame)
cv2.imshow("undistorted %s" % (undistorted_frame.shape,), undistorted_frame)
cv2.imshow("cropped %s" % (cropped_frame.shape,), cropped_frame)
cv2.waitKey(10)
示例3: undistort_images
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort_images(src, dst):
"""
undistort the images in src folder to dst folder
"""
# load dst, mtx
pickle_file = open("../camera_cal/camera_cal.p", "rb")
dist_pickle = pickle.load(pickle_file)
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
pickle_file.close()
# loop the image folder
image_files = glob.glob(src+"*.jpg")
for idx, file in enumerate(image_files):
print(file)
img = mpimg.imread(file)
image_dist = cv2.undistort(img, mtx, dist, None, mtx)
file_name = file.split("\\")[-1]
print(file_name)
out_image = dst+file_name
print(out_image)
image_dist = cv2.cvtColor(image_dist, cv2.COLOR_RGB2BGR)
cv2.imwrite(out_image, image_dist)
示例4: undistort
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort(frame, mtx, dist, verbose=False):
"""
Undistort a frame given camera matrix and distortion coefficients.
:param frame: input frame
:param mtx: camera matrix
:param dist: distortion coefficients
:param verbose: if True, show frame before/after distortion correction
:return: undistorted frame
"""
frame_undistorted = cv2.undistort(frame, mtx, dist, newCameraMatrix=mtx)
if verbose:
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0].imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
ax[1].imshow(cv2.cvtColor(frame_undistorted, cv2.COLOR_BGR2RGB))
plt.show()
return frame_undistorted
示例5: imageCallback
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def imageCallback(self, msg):
try:
# Convert your ROS Image message to OpenCV
cv2_img = bridge.imgmsg_to_cv2(msg, "rgb8")
if self.first_msg:
shape = cv2_img.shape
min_length = min(shape[0], shape[1])
up_margin = int((shape[0] - min_length) / 2) # row
left_margin = int((shape[1] - min_length) / 2) # col
self.valid_box = [up_margin, up_margin + min_length, left_margin, left_margin + min_length]
print("origin size: {}x{}".format(shape[0],shape[1]))
print("crop each image to a square image, cropped size: {}x{}".format(min_length, min_length))
self.first_msg = False
undistort_image = cv2.undistort(cv2_img, self.camera_matrix, self.distortion_coefficients)
self.valid_img = undistort_image[self.valid_box[0]:self.valid_box[1], self.valid_box[2]:self.valid_box[3]]
except CvBridgeError as e:
print("CvBridgeError:", e)
示例6: preprocess
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def preprocess(self, image, scale, altitude):
#remove distortion from video
if self.undistort:
image = cv2.undistort(image,self.matrix, self.distortion)
#crop image
if altitude > self.resize_alt_thres:
img_size = Point(image.shape[1], image.shape[0])
image, origin = roi(image, img_size * scale, img_size/2)
#subsample image
else:
image = cv2.resize(image,(0,0), fx = scale,fy = scale)
scale = 1.0
return image, scale
# if starting from mavproxy
示例7: image_to_world
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def image_to_world(self, image_px, z):
"""
Project image points with defined world z to world coordinates.
:param image_px: image points
:type image_px: numpy.ndarray, shape=(2 or 3, n)
:param z: world z coordinate of the projected image points
:type z: float
:return: n projective world coordinates
:rtype: numpy.ndarray, shape=(3, n)
"""
if image_px.shape[0] == 3:
image_px = p2e(image_px)
image_undistorted = self.undistort(image_px)
tmpP = np.hstack((self.P[:, [0, 1]], self.P[:, 2, np.newaxis] * z + self.P[:, 3, np.newaxis]))
world_xy = p2e(np.linalg.inv(tmpP).dot(e2p(image_undistorted)))
return np.vstack((world_xy, z * np.ones(image_px.shape[1])))
示例8: undistort_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort_image(img, mtx, dist, newcameramtx=None):
"""
Use camera intrinsics to undistort raw image
:param img: Raw Image
:param mtx: Camera Intrinsics matrix
:param dist: Distortion Coefficient
:param newcameramtx: Camera Intrinsics matrix after correction
:return: Undistorted image
"""
return cv2.undistort(src=img, cameraMatrix=mtx,
distCoeffs=dist, newCameraMatrix=newcameramtx)
示例9: undistort_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort_image(imagepath, calib_file, visulization_flag):
""" undistort the image and visualization
:param imagepath: image path
:param calib_file: includes calibration matrix and distortion coefficients
:param visulization_flag: flag to plot the image
:return: none
"""
mtx, dist = load_calibration(calib_file)
img = cv2.imread(imagepath)
# undistort the image
img_undist = cv2.undistort(img, mtx, dist, None, mtx)
img_undistRGB = cv2.cvtColor(img_undist, cv2.COLOR_BGR2RGB)
if visulization_flag:
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
f, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(imgRGB)
ax1.set_title('Original Image', fontsize=30)
ax1.axis('off')
ax2.imshow(img_undistRGB)
ax2.set_title('Undistorted Image', fontsize=30)
ax2.axis('off')
plt.show()
return img_undistRGB
示例10: undistort_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort_image(self, img, Kundistortion=None):
"""
Transform grayscale image such that radial distortion is removed.
:param img: input image
:type img: np.ndarray, shape=(n, m) or (n, m, 3)
:param Kundistortion: camera matrix for undistorted view, None for self.K
:type Kundistortion: array-like, shape=(3, 3)
:return: transformed image
:rtype: np.ndarray, shape=(n, m) or (n, m, 3)
"""
if Kundistortion is None:
Kundistortion = self.K
if self.calibration_type == 'opencv':
return cv2.undistort(img, self.K, self.opencv_dist_coeff, newCameraMatrix=Kundistortion)
elif self.calibration_type == 'opencv_fisheye':
return cv2.fisheye.undistortImage(img, self.K, self.opencv_dist_coeff, Knew=Kundistortion)
else:
xx, yy = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))
img_coords = np.array([xx.ravel(), yy.ravel()])
y_l = self.undistort(img_coords, Kundistortion)
if img.ndim == 2:
return griddata(y_l.T, img.ravel(), (xx, yy), fill_value=0, method='linear')
else:
channels = [griddata(y_l.T, img[:, :, i].ravel(), (xx, yy), fill_value=0, method='linear')
for i in xrange(img.shape[2])]
return np.dstack(channels)
示例11: _undistort_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def _undistort_image(self, image):
if self._camera_matrix is None or self._distortion_coefficients is None:
import warnings
warnings.warn("Undistortion has no effect because <camera_matrix>/<distortion_coefficients> is None!")
return image
h, w = image.shape[:2]
new_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(self._camera_matrix,
self._distortion_coefficients, (w, h),
1,
(w, h))
undistorted = cv2.undistort(image, self._camera_matrix, self._distortion_coefficients, None,
new_camera_matrix)
return undistorted
示例12: run
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def run(self) -> None:
while True:
if self.config.demo.display_on_screen:
self._wait_key()
if self.stop:
break
ok, frame = self.cap.read()
if not ok:
break
undistorted = cv2.undistort(
frame, self.gaze_estimator.camera.camera_matrix,
self.gaze_estimator.camera.dist_coefficients)
self.visualizer.set_image(frame.copy())
faces = self.gaze_estimator.detect_faces(undistorted)
for face in faces:
self.gaze_estimator.estimate_gaze(undistorted, face)
self._draw_face_bbox(face)
self._draw_head_pose(face)
self._draw_landmarks(face)
self._draw_face_template_model(face)
self._draw_gaze_vector(face)
self._display_normalized_image(face)
if self.config.demo.use_camera:
self.visualizer.image = self.visualizer.image[:, ::-1]
if self.writer:
self.writer.write(self.visualizer.image)
if self.config.demo.display_on_screen:
cv2.imshow('frame', self.visualizer.image)
self.cap.release()
if self.writer:
self.writer.release()
示例13: undistort_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort_image(self, img):
return cv2.undistort(src=img, cameraMatrix=self.__mtx,
distCoeffs=self.__dist, newCameraMatrix=None)
示例14: lane_process
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def lane_process(img, visualization=False):
start = timer()
# resize the input image according to scale
img_undist_ = cv2.undistort(img, mtx, dist, None, mtx)
img_undist = cv2.resize(img_undist_, (0,0), fx=1/input_scale, fy=1/input_scale)
# find the binary image of lane/edges
img_binary = find_edges(img_undist)
# warp the image to bird view
binary_warped = warper(img_binary, M) # get binary image contains edges
# crop the binary image
binary_sub = np.zeros_like(binary_warped)
binary_sub[:, int(150/input_scale):int(-80/input_scale)] = binary_warped[:, int(150/input_scale):int(-80/input_scale)]
# start detector or tracker to find the lanes
ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])
if left_lane.detected: # start tracker
tracker(binary_sub, ploty, visualization)
else: # start detector
detector(binary_sub, ploty, visualization)
# average among the previous N frames to get the averaged lanes
left_lane.process(ploty)
right_lane.process(ploty)
# measure the lane curvature
curvature, curve_direction = measure_lane_curvature(ploty, left_lane.mean_fitx, right_lane.mean_fitx)
# compute the car's off-center in meters
offcenter, pts = compute_car_offcenter(ploty, left_lane.mean_fitx, right_lane.mean_fitx, img_undist)
# compute the processing frame rate
end = timer()
fps = 1.0 / (end - start)
# combine all images into final video output (only for visualization purpose)
_, single_view, lane_info = create_output_frame(offcenter, pts, img_undist_, fps, curvature, curve_direction, binary_sub)
return img_undist_, single_view, lane_info
示例15: undistort_crop
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import undistort [as 別名]
def undistort_crop(orig_img):
#undistort and crop
dst = cv2.undistort(orig_img, mtx, dist, None, newcameramtx)
x,y,w,h = roi
crop_frame = dst[y:y+h, x:x+w]
return crop_frame