python实现得到两个图片不相似的地方
时间: 2023-05-14 15:07:31 浏览: 52
可以使用Python的Pillow库来实现这个功能。具体步骤如下:
1. 使用Pillow库中的Image模块打开两张图片,可以使用open()方法。
2. 将两张图片转换为相同的大小,可以使用resize()方法。
3. 将两张图片转换为灰度图像,可以使用convert()方法。
4. 使用Pillow库中的ImageChops模块对两张灰度图像进行比较,可以使用difference()方法。
5. 对比较结果进行阈值处理,得到不同的像素点坐标。
6. 将不同的像素点标记在原图上,可以使用Pillow库中的ImageDraw模块。
以下是示例代码:
```python
from PIL import Image, ImageChops, ImageDraw
def get_diff_pixels(img1, img2, threshold=50):
# 打开图片
img1 = Image.open(img1)
img2 = Image.open(img2)
# 转换为相同大小
img1 = img1.resize(img2.size)
# 转换为灰度图像
img1 = img1.convert('L')
img2 = img2.convert('L')
# 比较两张灰度图像
diff = ImageChops.difference(img1, img2)
# 阈值处理,得到不同的像素点坐标
diff_pixels = []
for x in range(diff.size[0]):
for y in range(diff.size[1]):
if diff.getpixel((x, y)) > threshold:
diff_pixels.append((x, y))
return diff_pixels
def mark_diff_pixels(img, diff_pixels, mark_color=(255, 0, 0)):
# 打开图片
img = Image.open(img)
# 标记不同的像素点
draw = ImageDraw.Draw(img)
for pixel in diff_pixels:
draw.point(pixel, fill=mark_color)
# 保存标记后的图片
img.save('marked_diff.png')
# 示例
diff_pixels = get_diff_pixels('img1.png', 'img2.png')
mark_diff_pixels('img1.png', diff_pixels)
```
这段代码可以得到两张图片不相似的地方,并将不同的像素点标记在原图上,保存为marked_diff.png。