python - 如何使用 OpenCV 处理的图像将小图像粘贴到 python 中心的另一个大图像上?

标签 python python-3.x python-imaging-library opencv3.0

我正在学习 OpenCV 并尝试将小图像粘贴到大图像上。但是,它显示了一个错误,因为两个图像应该具有相同的大小。 我也尝试遵循提供的建议 ( How to paste an image onto a larger image using Pillow? ) 和 ( How do you composite an image onto another image with PIL in Python? )

   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)

最终输出图像应居中。

最佳答案

这是一个纯 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")

输入图像:-

enter image description here

输出图像:-

enter image description here

代码本身是不言自明的,但您可能想知道为什么我们要将裁剪后的图像来回转换为 RGBA。这样做的原因是,因为如果我们在 PIL 中旋转非 alpha 图像,我们最终会在图像上出现像素值不再存在的黑条/边缘 (read this question for more)。但是,如果我们对 alpha 图像执行相同的操作,即通过 rotate() 传递 alpha 图像,则空像素值最终会完全透明(或 alpha = 0)。

关于python - 如何使用 OpenCV 处理的图像将小图像粘贴到 python 中心的另一个大图像上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56866759/

相关文章:

python - "returns iterator"在python中是什么意思?

python - 有没有更好的方法来管理 Python 中 Tkinter 的位置?

python - 为什么 str.count ('' ) 和 len(str) 给出不同的输出?

python-3.x - 如何执行 ipython notebook

python - 为什么使用 FuncAnimation 绘图时点不移动?

python - 使用 Python 重叠 2 个 RGBA 图像

python - 错误导入 awswrangler : AttributeError: module 'multiprocessing' has no attribute 'connection'

python - 如何将 sRGB 转换为线性 sRGB 以计算 opencv 中的色彩校正矩阵? (CCM)

python - PIL简单渐变和TypeError : an integer is required

python - 用红色或黑色像素替换2D矩阵值