【发布时间】:2020-11-23 20:41:57
【问题描述】:
我使用 cv2.warpAffine() 将 3 个图像旋转 180 度,然后使用 cv2.hconcat() 将它们水平连接。这是在图像之间添加一个 1 像素宽的黑色列,但来自 img.shape 的图像宽度是正确的。如果我不旋转它们,图像看起来不错,没有黑柱。所有 3 张图片均为 1920 宽 x 1200 高。
如何消除黑柱?它类似于 - warpAffine
Scipy 不会发生这种情况。注释掉的代码 (ndimage.rotate()) 是我用 Scipy 解决它的方法 - 从这里here。 Scipy 代码比较慢,我有数千张图片。
编辑
一分钟后,我现在使用 numpy 将矩阵旋转 90 度两次。来自numpy.rot90() 这似乎更快。它也在下面的注释代码中。对于非 90 度角,我会坚持使用 opencv 中的 warpAffine。
import cv2
import numpy as np
from scipy import ndimage
def rotate_image(mat, angle):
""" Rotates an image (angle in degrees) and expands image to avoid cropping
"""
height, width = mat.shape[:2] # image shape has 3 dimensions
image_center = (width/2, height/2) # getRotationMatrix2D needs coordinates in reverse order (width, height) compared to shape
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0000)
# rotation calculates the cos and sin, taking absolutes of those.
abs_cos = abs(rotation_mat[0,0])
abs_sin = abs(rotation_mat[0,1])
# find the new width and height bounds
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
# find the new width and height bounds
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
print(f'Bounds w = {bound_w} Bound H = {bound_h}')
# subtract old image center (bringing image back to original) and adding the new image center coordinates
rotation_mat[0, 2] += bound_w/2 - image_center[0]
rotation_mat[1, 2] += bound_h/2 - image_center[1]
# rotate image with the new bounds and translated rotation matrix
rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))
return rotated_mat
left_img = cv2.imread(r"F:\Basler\1595525164.242553_l.tiff",0)
cent_img = cv2.imread(r"F:\Basler\1595525164.242553_c.tiff",0)
rigt_img = cv2.imread(r"F:\Basler\1595525164.242553_r.tiff",0)
print(f'Shape = {rigt_img.shape} is {len(rigt_img.shape)}')
angle = 180
left_rot = rotate_image(left_img, angle)
cent_rot = rotate_image(cent_img, angle)
rigt_rot = rotate_image(cent_img, angle)
'''
left_rot = ndimage.rotate(left_img, angle)
cent_rot = ndimage.rotate(cent_img, angle)
rigt_rot = ndimage.rotate(rigt_img, angle)
THIS SEEMS THE FASTEST
left_rot = np.rot90(left_img,2)
cent_rot = np.rot90(cent_img,2)
rigt_rot = np.rot90(rigt_img,2)
'''
#lane_img = np.concatenate((left_rot, cent_rot, rigt_rot), axis=1)
lane_img = cv2.hconcat([left_rot, cent_rot, rigt_rot])
print(f'Size = {lane_img.shape}')
cv2.imwrite(r'C:\Users\Cary\Desktop\Junk\lane1.tiff', lane_img)
【问题讨论】:
-
我现在不能运行你的代码,但是在你hconcat它们之前,它们有不需要的栏吗?
-
当您可以简单地镜像图像时,为什么要将图像旋转 180 度?根据旋转功能的实现方式,它可能比镜像慢并且不是无损的。
-
你好@Cary H,你能测试一下下面的答案吗?
-
他们有不受欢迎的旋转栏。图像大小为 1920 x 1200 ,前后。我还没有测试边框添加。我现在会。此外,mirror 和 rotate 与 Karson 大不相同。
标签: python-3.x opencv image-processing