Raj*_*hra 3 python python-imaging-library python-3.x opencv3.0
我正在学习 OpenCV 并尝试将小图像粘贴到大图像上。但是,它显示了一个错误,因为两个图像应该具有相同的大小。我还尝试遵循提供的建议(如何使用 Pillow 将图像粘贴到更大的图像上?)和(如何使用 Python 中的 PIL 将图像合成到另一个图像上?)
import cv2 as cv
from scipy import ndimage
img1 = cv.imread('Please put your file name')
top_left_x = min([x1,x2,x3,x4])
top_left_y = min([y1,y2,y3,y4])
bot_right_x = max([x1,x2,x3,x4])
bot_right_y = max([y1,y2,y3,y4])
y_right =bot_right_y + 1
x_right =bot_right_x + 1
cropped = img[top_left_y: y_right, top_left_x: x_right]
rotate = ndimage.rotate(cropped, ang)
Run Code Online (Sandbox Code Playgroud)
最终输出图像应位于中心。
这是一个纯PIL解决方案:-
from PIL import Image
img1 = Image.open(r"Source_Image_path")
# The values used to crop the original image (will form a bbox)
x1, y1, x2, y2 = 10, 10, 400, 400
# The angle at which the cropped Image must be rotated
angle = 50
# cropping the original image
img = img1.crop((x1, y1, x2, y2))
# Firstly converting the Image mode to RGBA, and then rotating it
img = img.convert("RGBA").rotate(angle, resample=Image.BICUBIC)
# calibrating the bbox for the beginning and end position of the cropped image in the original image
# i.e the cropped image should lie in the center of the original image
x1 = int(.5 * img1.size[0]) - int(.5 * img.size[0])
y1 = int(.5 * img1.size[1]) - int(.5 * img.size[1])
x2 = int(.5 * img1.size[0]) + int(.5 * img.size[0])
y2 = int(.5 * img1.size[1]) + int(.5 * img.size[1])
# pasting the cropped image over the original image, guided by the transparency mask of cropped image
img1.paste(img, box=(x1, y1, x2, y2), mask=img)
# converting the final image into its original color mode, and then saving it
img1.convert(img1.mode).save("Destination_path")
Run Code Online (Sandbox Code Playgroud)
输入图像:-
输出图像:-
代码本身是不言自明的,但您可能想知道为什么我们将裁剪后的图像来回转换为RGBA. 原因是,如果我们在 PIL 中旋转非 alpha 图像,最终会在图像上出现黑条/边缘,其中像素值不再存在(请阅读此问题了解更多信息)。但是,如果我们对 alpha 图像执行相同的操作,即通过 alpha 图像传递,rotate()那么空像素值最终将完全透明(或 alpha = 0)。
| 归档时间: |
|
| 查看次数: |
6896 次 |
| 最近记录: |