在Python中标记2张图片之间的差异 [英] Mark the difference between 2 pictures in Python

查看:90
本文介绍了在Python中标记2张图片之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始玩 Pillow.我正在比较 Python 3.3 中的两张图片,并希望将差异保存为图像.

I have recently started to play with Pillow. I am comparing two pictures in Python 3.3 and want to save the difference as an image.

from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw

file1 = '300.jpg'
file2 = '300.jpg'

im1 = Image.open(file1)
im2 = Image.open(file2)

diff = ImageChops.difference(im1, im2).getbbox()
draw = ImageDraw.Draw(im2)
draw.rectangle(diff)
im2.convert('RGB').save('file3.jpg')

但我总是得到一个TypeError:参数必须是序列

我相信这发生在 draw.rectangle(diff)我怎样才能摆脱错误?

I believe this happens at draw.rectangle(diff) How can I get rid of the error?

谢谢.

推荐答案

来自 PIL 文档:

PIL.ImageDraw.Draw.rectangle(xy, fill=None, outline=None)绘制一个矩形.

参数:
xy – 定义边界框的四个点.

Parameters:
xy – Four points to define the bounding box.

[(x0, y0), (x1, y1)][x0, y0, x1, y1] 的序列.第二个点就在绘制的矩形之外.

Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1]. The second point is just outside the drawn rectangle.

outline – 用于轮廓的颜色.

outline – Color to use for the outline.

fill – 用于填充的颜色.

fill – Color to use for the fill.

这意味着您应该传递一个序列,并且来自 文档 以及:

This means that you should pass a sequence, and from the documentation as well:

Image.getbbox()

计算图像中非零区域的边界框.

Calculates the bounding box of the non-zero regions in the image.

返回:边界框作为定义左边的 4 元组返回,上、右、下像素坐标.如果图像完全为空,此方法返回 None.

Returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. If the image is completely empty, this method returns None.

所以问题是你将一个 4 元组传递给一个期望 [(x0, y0), (x1, y1)][x0, y0, x1, y1]

So the problem is that you pass a 4 tuple to a function that expects a sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1]

你可以用 list() 文字包裹你的 4 元组以获得函数期望的第二个选项:

You can wrap your 4 tuple with list() literal to get the second option of what the function expects:

from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw

file1 = '300.jpg'
file2 = '300.jpg'

im1 = Image.open(file1)
im2 = Image.open(file2)

diff = ImageChops.difference(im1, im2).getbbox()
draw = ImageDraw.Draw(im2)
diff_list = list(diff) if diff else []
draw.rectangle(diff_list)
im2.convert('RGB').save('file3.jpg')

或者如果您想将输入替换为第一种 rectangle 期望您可以执行以下操作:

Or if you want to replace the input to the first type rectangle expects you can do the following:

from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw

file1 = '300.jpg'
file2 = '300.jpg'

im1 = Image.open(file1)
im2 = Image.open(file2)

diff = ImageChops.difference(im1, im2).getbbox()
draw = ImageDraw.Draw(im2)
diff_list_tuples = >>> [diff[0:2], diff[2:]] if diff else [(None, None), (None, None)]
draw.rectangle(diff_list)
im2.convert('RGB').save('file3.jpg')

这篇关于在Python中标记2张图片之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆