与第一版相比,我正在尝试使代码更健壮。目的是通过比较图像A和图像B以获得图像C来生成最终的单个图像。目前,我正在努力显示由黑线组成的图像中的差异。在这种情况下,将是图像A和B。我有一个工作方法,可以调整图像大小并完成预处理(调整大小,减少噪声等)。我开发来显示差异的代码(图像C)如下所示:
np_image_A = np.array(image_A)
np_image_B = np.array(image_B)
# Set the green and red channels respectively to 0. Leaves a blue image
np_image_A[:, :, 1] = 0
np_image_A[:, :, 2] = 0
# Set the blue channels to 0.
np_image_B[:, :, 0] = 0
# Add the np images after color modification
overlay_image = cv2.add(np_image_A, np_image_B)
我目前认为这不够强大,可能会导致一些问题。我想使用一种方法来显示单个图像中图像A和B之间的图像差异。并且为图像A分配一种颜色的差异,为图像B分配另一种颜色(例如蓝色和红色,黑色表示相同的区域)。下图中突出显示了该图像:
为了解决这个问题,我从StackOverflow获得了一些帮助,现在有了一种在OpenCV中使用屏蔽和合并的方法。我发现的问题是仅显示了附加更改,并且如果删除了某个项目,则该项目不会显示在差异图像中。
这是更新后的代码,它使我成为所寻求解决方案的一部分。此代码的问题是,它生成在图像D中找到的内容,而不是在图像C中找到的内容。代码两次,切换img = imageA和imageB,但是由于某种原因输出被破坏了。
# load image A as color image
img = cv2.imread('1a.png')
# load A and B as grayscale
imgA = cv2.imread('1a.png',0)
imgB = cv2.imread('1b.png',0)
# invert grayscale images for subtraction
imgA_inv = cv2.bitwise_not(imgA)
imgB_inv = cv2.bitwise_not(imgB)
# subtract the original (A) for the new version (B)
diff = cv2.subtract(imgB_inv, imgA_inv)
# split color image A into blue,green,red color channels
b,g,r = cv2.split(img)
# merge channels back into image, subtracting the diff from
# the blue and green channels, leaving the shape of diff red
res = cv2.merge((b-diff,g-diff,r))
# display result
cv2.imshow('Result',res)
cv2.waitKey(0)
cv2.destroyAllWindows()
我正在寻找的结果是图像C,但是目前我只能使用修改后的代码获得图像D。
答案 0 :(得分:1)
您快到了,但是您需要创建两个单独的差异。一个差异表示位于A中但不在B中的黑色像素,另一个差异表示位于B中但不在A中的黑色像素。
import cv2
import numpy as np
# load A and B as grayscale
imgA = cv2.imread('1a.png',0)
imgB = cv2.imread('1b.png',0)
# invert grayscale images for subtraction
imgA_inv = cv2.bitwise_not(imgA)
imgB_inv = cv2.bitwise_not(imgB)
# create two diffs, A - B and B - A
diff1 = cv2.subtract(imgB_inv, imgA_inv)
diff2 = cv2.subtract(imgA_inv, imgB_inv)
# create a combined image of the two inverted
combined = cv2.add(imgA_inv, imgB_inv)
combined_inv = cv2.bitwise_not(combined)
# convert the combined image back to rbg,
# so that we can modify individual color channels
combined_rgb = cv2.cvtColor(combined_inv, cv2.COLOR_GRAY2RGB)
# split combined image into blue,green,red color channels
b,g,r = cv2.split(combined_rgb)
# merge channels back into image, adding the first diff to
# the red channel and the second diff to the blue channel
res = cv2.merge((b+diff2,g,r+diff1))
# display result
cv2.imshow('Result',res)
cv2.waitKey(0)
cv2.destroyAllWindows()