如果大于某个阈值,则将灰度图像中的像素着色为红色

Color the pixel red in gray-scale image if is greater than some threshold

在计算了两个灰度图像 img1 和 img2 的像素差异后,我必须设置一个特定的阈值,即 diff 的平均值。现在,如果 img1 > threshold 中的像素值,我必须将该像素着色为红色。如何将该像素着色为红色并将其他像素着色为灰度?我很熟悉通过将大于阈值的像素值分配为 1 并将其他像素值分配为 0 来生成二进制掩码,但我想将该像素着色为红色。

img1 = cv2.imread(path,0)
img2 = cv2.imread(path,0)

diff = cv2.absdiff(img1, img2)
threshold=int(np.mean(diff))

您可以这样做,从以下开始:

import cv2
img1 = cv2.imread('Bean.jpg',0)
img2 = cv2.imread('saltnpepperBean.jpg',0)

diff = cv2.absdiff(img1, img2)
threshold=int(np.mean(diff))

# Make colour version of input image so we can put red pixels in it
resultRGB = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR)

# Colorize all pixels above threshold with red 
resultRGB[diff>3*threshold] = 0,0,255

# Save to disk
cv2.imwrite('result.jpg',resultRGB)