所以对于我正在进行的这个项目,我有 2 张照片。这两张照片需要拼接在一起,一张在上面,一张在下面,然后你就可以看到整个画面了。关于我应该使用哪个模块来执行此操作的任何想法?
问问题
35571 次
5 回答
34
这是使用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
于 2015-12-16T00:02:23.467 回答
25
python 成像库(更新的链接)将在早餐时吃掉该任务。
请参阅教程,特别是“剪切、粘贴和合并图像”部分以获得一些相关帮助。
对于粗略的轮廓,使用 加载两个图像,通过使用属性和一些添加Image.open
找出输出图像的大小,创建输出图像,然后使用方法将两个原始图像过去。size
Image.new
paste
于 2012-05-18T17:52:39.690 回答
3
这是来自 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)
于 2013-08-18T02:40:51.640 回答
2
使用numpy.hstack()
或numpy.vstack()
基于您是否希望图像彼此相邻或彼此重叠。如果图像是 numpy 不接受的奇怪格式,您可以将它们转换为 numpy 数组。确保设置dtype=np.uint8
是否使用该np.asarray()
方法将图像解释为数组。
于 2019-03-29T00:00:54.213 回答
1
我做了这样的垂直拼接 - 它与@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 行 - 只有高度会改变拼接
box=(width1, 0)
将第 28 行更改为的第二张图片粘贴到box=(0, height1)
于 2019-06-06T21:17:51.237 回答