Как удалить строку черных пикселей из вращения OpenCV WarpAffine - PullRequest
0 голосов
/ 03 августа 2020

Я поворачиваю 3 изображения на 180 градусов с помощью cv2.warpAffine (), а затем объединяю их по горизонтали с помощью cv2.hconcat (). Это добавляет черный столбец шириной 1 пиксель между изображениями, но ширина изображения из img.shape правильная. Если я не поверну их, изображение будет выглядеть хорошо, без черных столбцов. Все 3 изображения имеют размер 1920 x 1200.

Как удалить черный столбец? Это похоже на - warpAffine

Это не происходит с Scipy. Закомментированный код (ndimage.rotate ()) - это то, как я решил это с помощью Scipy - отсюда здесь . Код Scipy работает медленнее, и у меня есть тысячи изображений.

EDIT

Через минуту я теперь использую numpy, чтобы дважды повернуть матрицу на 90 градусов. От numpy .rot90 () Это кажется еще быстрее. Это также есть в закомментированном коде ниже. Для углов, отличных от 90 градусов, я буду использовать warpAffine от opencv.

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)

1 Ответ

0 голосов
/ 03 августа 2020

Строку можно удалить, добавив по одной дополнительной строке с каждой стороны изображения до поворота с помощью copyMakeBorder:

after_mat = cv2.copyMakeBorder(
        mat,
        top=1,
        bottom=1,
        left=1,
        right=1,
        borderType=cv2.BORDER_REFLECT
    )

# rotate image with the new bounds and translated rotation matrix
rotated_mat = cv2.warpAffine(after_mat, rotation_mat, (bound_w, bound_h))

Я не знаю причину появления дополнительной строки (возможно, сдвиг из-за поворота ?), но приведенный выше код может подавить его, надеюсь, без побочных эффектов.

...