除了使用 PIL 库中的 ImageChops.difference()
方法以外,还有其他方法可以实现单点比色。以下是其中一些示例:
- 使用 numpy 库进行单点比色
import numpy as np
# 读取图片
img1 = np.asarray(Image.open('image1.png'))
img2 = np.asarray(Image.open('image2.png'))
# 计算差值
diff = np.abs(img1 - img2)
# 定义阈值
threshold = 30
# 找出差值大于阈值的像素点
diff_pixels = np.where(diff > threshold)
# 输出差异像素点坐标
for y, x in zip(diff_pixels[0], diff_pixels[1]):
print(f'Different pixel at ({x}, {y})')
- 使用 OpenCV 库进行单点比色
import cv2
# 读取图片
img1 = cv2.imread('image1.png')
img2 = cv2.imread('image2.png')
# 将图片转为灰度图
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 计算差值
diff = cv2.absdiff(gray1, gray2)
# 定义阈值
threshold = 30
# 找出差值大于阈值的像素点
diff_pixels = cv2.findNonZero(diff > threshold)
# 输出差异像素点坐标
for pixel in diff_pixels:
x, y = pixel[0]
print(f'Different pixel at ({x}, {y})')
- 使用 scikit-image 库进行单点比色
from skimage import io, color
# 读取图片
img1 = io.imread('image1.png')
img2 = io.imread('image2.png')
# 将图片转为 Lab 色彩空间
lab1 = color.rgb2lab(img1)
lab2 = color.rgb2lab(img2)
# 计算差值
diff = np.sqrt(np.sum((lab1 - lab2) ** 2, axis=2))
# 定义阈值
threshold = 30
# 找出差值大于阈值的像素点
diff_pixels = np.where(diff > threshold)
# 输出差异像素点坐标
for y, x in zip(diff_pixels[0], diff_pixels[1]):
print(f'Different pixel at ({x}, {y})')
以上是三种常见的单点比色方法示例,根据实际情况选择适合自己的方法。