从用PIL模块创建的两个图像im1和im2开始,我们有相应的黑白图像,
Starting with two images im1 and im2 created with the PIL module, we have the corresponding black and white images,
bw_im1 = im1.convert('1')和
bw_im2 = im2.convert('1')bw_im2和bw_im2的每个像素为0或256.
Each pixel of bw_im2 and bw_im2 is either 0 or 256.
假设bw_im2和bw_im2的大小相同.
如何对所有对应的条目进行XOR,然后将它们求和 上吗?
How do you XOR all the corresponding entries and then sum them up?
我的工作
我编写了以下 stub/概念证明 Python程序,但担心使用代码(解包/翻译)会很复杂.可能会有更直接有效的方法来处理两个图像中的像素.
I wrote the following stub / proof of concept Python program, but worried that using the code (unpacking/translating over) would be complicated. There might be a more direct and efficient way to process the pixels in the two images.
import numpy as np M = np.zeros((2, 3)) M[0,2] = 255 M[1,0] = 255 M[1,1] = 255 print(M) N = np.zeros((2, 3)) N = np.zeros((2, 3)) N[0,2] = 255 N[1,1] = 255 N[1,2] = 255 print(N) list_M = list(M) list_N = list(N) xor_signal = 0 for row in range(0, len(list_M)): for col in range(0,len(list_M[row])): xor_signal = xor_signal + int(bool(list_M[row][col]) != bool(list_N[row][col])) print(xor_signal)输出
[[ 0. 0. 255.] [255. 255. 0.]] [[ 0. 0. 255.] [ 0. 255. 255.]] 2推荐答案
您可以像这样使用PIL的 ImageChops :
You can use PIL's ImageChops like this:
#!/usr/local/bin/python3 import numpy as np from PIL import Image, ImageChops # Open images im1 = Image.open("im1.png") im2 = Image.open("im2.png") result = ImageChops.logical_xor(im1,im2) result.save('result.png')因此,如果您从以下两个开始:
So, if you start with these two:
结果将是:
当然,如果您是物理学家,则可以这样写;-)
Of course, if you are a physicist, you can write that like this ;-)
#!/usr/local/bin/python3 from PIL import Image, ImageChops ImageChops.logical_xor(Image.open("im1.png"), Image.open("im2.png")).save('result.png')
或者您可以像这样使用Numpy的XOR:
Or you can use Numpy's XOR like this:
#!/usr/local/bin/python3 import numpy as np from PIL import Image # Open images im1 = Image.open("im1.png") im2 = Image.open("im2.png") # Make into Numpy arrays im1np = np.array(im1)*255 im2np = np.array(im2)*255 # XOR with Numpy result = np.bitwise_xor(im1np, im2np).astype(np.uint8) # Convert back to PIL image and save Image.fromarray(result).save('result.png')您可以通过在末尾添加像素来求和:
You can sum the pixels by adding this at the end:
print('Sum: {}'.format(np.sum(result)))
或者您不必费心编写任何Python,只需在终端中输入以下 ImageMagick 命令:
Or you can not bother writing any Python and just type the following ImageMagick command into your Terminal:
magick im1.png im2.png -evaluate-sequence xor result.png如果您使用的是v6或更早的版本,请改用以下内容:
If you are using v6, or older, use the following instead:
convert im1.png im2.png -evaluate-sequence xor result.png更多推荐
对两个黑白图像进行异或运算
发布评论