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

标签 python python-imaging-library cv2

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

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

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

最佳答案

你可以做这样的事情,从以下开始:

enter image description here enter image description here

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)

enter image description here

关于python - 如果大于某个阈值,则将灰度图像中的像素着色为红色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53077364/

相关文章:

python - 如何将 joblib 转储保存到另一个文件夹?

python - 将图像更改为 numpy 数组后,我只想导入 1 个 channel

opencv - ubuntu 中 cv2 的安装问题

python-3.x - 导入 cv2 dll 加载失败

python - 如何强制除法为 float ?除法不断四舍五入为0?

python - Elasticsearch 日期范围未返回任何命中

python - 具有随机像素颜色的 100x100 图像

python - 多个 PIL 图像合并为一个图

python - 使用 PIL 和 cv2 压缩 PNG

python - 如何在scrapy中设置json输出的键值对?