Home > Back-end >  Rotate an image in python and fill the cropped area with image
Rotate an image in python and fill the cropped area with image

Time:02-03

Have a look at the image and it will give you the better idea what I want to achieve. I want to rotate the image and fill the black part of image just like in required image. enter image description here

# Read the image
img = cv2.imread("input.png")

# Get the image size
h, w = img.shape[:2]

# Define the rotation matrix
M = cv2.getRotationMatrix2D((w/2, h/2), 30, 1)

# Rotate the image
rotated = cv2.warpAffine(img, M, (w, h))

mask = np.zeros(rotated.shape[:2], dtype=np.uint8)
mask[np.where((rotated == [0, 0, 0]).all(axis=2))] = 255
img_show(mask)

From the code I am able to get the mask of black regions. Now I want to replace these black regions with the image portion as shown in the image enter image description here

CodePudding user response:

Use the borderMode parameter of warpAffine.

You want to pass the enter image description here

CodePudding user response:

I have an approach. You can first create a larger image consisting of 3 * 3 times your original image. When you rotate this image and only cut out the center of this large image, you have your desired result.

import cv2
import numpy as np

# Read the image
img = cv2.imread("input.png")

# Get the image size of the origial image
h, w = img.shape[:2]

# make a large image containing 3 copies of the original image in each direction
large_img = np.tile(img, [3,3,1])

cv2.imshow("large_img", large_img)

# Define the rotation matrix. Rotate around the center of the large image
M = cv2.getRotationMatrix2D((w*3/2, h*3/2), 30, 1)

# Rotate the image
rotated = cv2.warpAffine(large_img, M, (w*3, h*3))

# crop only the center of the image
cropped_image = rotated[w:w*2,h:h*2,:]

cv2.imshow("cropped_image", cropped_image)
cv2.waitKey(0)
  • Related