因此对于我正在研究的这个项目,我有2张照片。这两张照片需要拼接在一起,一张在顶部,一张在底部,然后你就可以看到整个画面了。关于我应该用什么模块来做这个的任何想法?
答案 0 :(得分:22)
请参阅tutorial特别是“剪切,粘贴和合并图像”部分以获取相关帮助。
对于粗略轮廓,使用Image.open
加载两个图像,使用size
属性找出输出图像的大小,并添加一些,使用Image.new
创建输出图像,然后使用paste
方法过去两个原始图像。
答案 1 :(得分:21)
这是使用Pillow的代码示例。希望它可以帮助别人!
from PIL import Image
def merge_images(file1, file2):
"""Merge two images into one, displayed side by side
:param file1: path to first image file
:param file2: path to second image file
:return: the merged Image object
"""
image1 = Image.open(file1)
image2 = Image.open(file2)
(width1, height1) = image1.size
(width2, height2) = image2.size
result_width = width1 + width2
result_height = max(height1, height2)
result = Image.new('RGB', (result_width, result_height))
result.paste(im=image1, box=(0, 0))
result.paste(im=image2, box=(width1, 0))
return result
答案 2 :(得分:2)
这是Jan Erik Solems计算机视觉与python书的一些代码;您可以编辑它以满足您的最高/最低需求
def stitchImages(im1,im2):
'''Takes 2 PIL Images and returns a new image that
appends the two images side-by-side. '''
# select the image with the fewest rows and fill in enough empty rows
rows1 = im1.shape[0]
rows2 = im2.shape[0]
if rows1 < rows2:
im1 = concatenate((im1,zeros((rows2-rows1,im1.shape[1]))), axis=0)
elif rows1 > rows2:
im2 = concatenate((im2,zeros((rows1-rows2,im2.shape[1]))), axis=0)
# if none of these cases they are equal, no filling needed.
return concatenate((im1,im2), axis=1)
答案 3 :(得分:0)
根据要图像彼此相邻还是位于顶部,使用numpy.hstack()或numpy.vstack()。如果图像是numpy不接受的某种奇怪格式,则可以将其转换为numpy数组。如果使用np.asarray()方法将图像解释为数组,请确保设置dtype = np.uint8。
答案 4 :(得分:0)
我像这样进行垂直缝合-这与@ d3ming的代码相同
07: def merge_images(file1, file2):
08: """Merge two images into one vertical image
09: :param file1: path to first image file
10: :param file2: path to second image file
11: :return: the merged Image object
12: """
13: image1 = Image.open(file1)
14: image2 = Image.open(file2)
15:
16: (width1, height1) = image1.size
17: (width2, height2) = image2.size
18:
19: # result_width = width1 + width2
20: result_width = width1
21: # result_height = max(height1, height2)
22: result_height = height1 + height2
23:
24: print (height2)
25:
26: result = Image.new('RGB', (result_width, result_height))
27: result.paste(im=image1, box=(0, 0))
28: result.paste(im=image2, box=(0, height1))
29: return result
19-22行-仅高度会改变以进行缝合
在第28行上粘贴第二张图片box=(width1, 0)
更改为box=(0, height1)