[英]Is there any way to merge multiple image into one single image in Python?
I want to merge multiple images into one single image horizontaly. 我希望将多个图像合并为一个单独的图像。 I tried to merge images through given code but it gives white image?
我试图通过给定的代码合并图像,但它提供白色图像? For merge Images I tried PIL .
对于合并图像我尝试了PIL。
import sys
from PIL import Image
def append_images(images,bg_color=(255,255,255), aligment='center'):
widths, heights = zip(*(i.size for i in images))
new_width = sum(widths)
new_height = max(heights)
new_im = Image.new('RGB', (new_width, new_height), color=bg_color)
offset = 0
for im in images:
y = 0
if aligment == 'center':
y = int((new_height - im.size[1])/2)
elif aligment == 'bottom':
y = new_height - im.size[1]
new_im.paste(im, (offset, y))
offset += im.size[0]
return new_im
date=input("Enter Date:")
l=['1.jpg','2.jpg','3.jpg']
images = map(Image.open,l)
combo_2 = append_images(images, aligment='center')
combo_2.save('combo_2.jpg')
I prefer working with OpenCV&Numpy combo. 我更喜欢使用OpenCV和Numpy组合。 That means working with arrays.
这意味着使用数组。 The code below simply take first image as starting point - Height.
下面的代码仅以第一张图片为起点-高度。 Any image you will append with it will be horizontaly stacked based on height.
您将附加的任何图像将根据高度进行水平叠加。 That means, appended image will be resized by the montage Height and then horizontally stacked to montage.
这意味着,附加的图像将根据蒙太奇高度调整大小,然后水平堆叠到蒙太奇。
Working Code 工作守则
import cv2
import numpy as np
image1 = cv2.imread("img1.jpg")[:,:,:3]
image2 = cv2.imread("img2.jpg")[:,:,:3]
class Montage(object):
def __init__(self,initial_image):
self.montage = initial_image
self.x,self.y = self.montage.shape[:2]
def append(self,image):
image = image[:,:,:3]
x,y = image.shape[0:2]
new_image = cv2.resize(image,(int(y*float(self.x)/x),self.x))
self.montage = np.hstack((self.montage,new_image))
def show(self):
cv2.imshow('montage',self.montage)
cv2.waitKey()
cv2.destroyAllWindows()
Firstly, you initialize class with first image which will define HEIGHT. 首先,使用将定义HEIGHT的第一个图像初始化类。 So if you want different height, pass into the class resized image.
因此,如果您想要不同的高度,请传入类调整大小的图像。 After that you can append horizontaly the image
之后,您可以水平附加图像
Usage 用法
>>> m = Montage(image1)
>>> m.append(image2)
>>> m.show()
Result in your case: 结果在您的情况下:
But generally it can work with totaly different sizes 但通常它可以使用完全不同的大小
Image 1 图片1
Image 2 图2
Montage 剪辑
Replace your line: 替换你的行:
images = map(Image.open,l)
with: 有:
images = [ Image.open(im) for im in l]
and it all works fine. 这一切都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.