如何在 Python 中检索高于基于平均值的阈值的总像素值

How to retrieve a total pixel value above an average-based threshold in Python

目前,我正在练习根据整个图像的平均值检索高于阈值的像素值的总和。 (我对 Python 很陌生)。我正在使用 Python 3.5.2,上面的代码是从我用来编写和试验代码的 Atom 程序中复制的。

目前,我只是在练习红色通道 - 但最终,我需要单独分析所有颜色通道。

我目前使用的完整代码:

import os  
from skimage import io  
from tkinter import *  
from tkinter.filedialog import askopenfilename  
def callback():  
    M = askopenfilename()       #to select a file  
    image = io.imread(M)        #to read the selected file  
    red = image[:,:,0]          #selecting the red channel  
    red_av = red.mean()         #average pixel value of the red channel  
    threshold = red_av + 100    #setting the threshold value  
    red_val = red > threshold  
    red_sum = sum(red_val)  
    print(red_sum)  
Button(text = 'Select Image', command = callback).pack(fill = X)  
mainloop()

现在,到目前为止一切正常,除了当我 运行 程序时,red_sum 结果是 threshold 以上的像素数,而不是像素总数.

我错过了什么?我在想我(可能是天真的)声明 red_val 变量的方式与它有关。

但是,如何检索高于阈值的总像素值?

当您执行 (red > threshold) 时,您得到了一个遮罩,所有高于阈值的红色像素都得到了值 1,否则得到了 0。现在要获取值,您只需将掩码与红色通道相乘即可。乘法会将所有小于阈值的值归零,并使超过阈值的值保持不变。

代码:

red_val = (red > threshold)*red
red_sum = sum(red_val)

我发现另一种有效的方法(提供总像素值)是使用屏蔽值:

import numpy.ma as ma
...    

red_val = ma.masked_outside(red, threshold, 255).sum()

SciPy.org documentation关于屏蔽的内容来看,它的作用是:

Mask an array outside a given interval.

在示例中,threshold(在我的问题中定义)和 255 区间之外的任何内容都是 'masked',并且在计算像素值总和时不具有特征.