【问题标题】:How to retrieve a total pixel value above an average-based threshold in Python如何在 Python 中检索高于基于平均值的阈值的总像素值
【发布时间】:2016-12-11 21:28:45
【问题描述】:

目前,我正在练习根据整个图像的平均值检索高于阈值的像素值的总和。 (我对 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_sumthreshold 上方的像素数,而不是像素总数。

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

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

【问题讨论】:

  • 不完全确定为什么,但是当我按上述方式编写时 - 我得到了 red_sum 的值列表 - 但如果我将总和行(正上方)更改为 red_sum = red_val.sum() 我得到一个数字答案。

标签: python python-3.x image-processing pixels threshold


【解决方案1】:

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

代码:

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

【讨论】:

  • 完美!你的解释也很有意义——一个非常好的简单方法,效果很好。
【解决方案2】:

我发现另一种可行的方法(提供总像素值)是使用掩码值:

import numpy.ma as ma
...    

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

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

屏蔽给定区间之外的数组。

在示例中,threshold(在我的问题中定义)和 255 的区间之外的任何内容都被“屏蔽”,并且在计算像素值总和时不具有特征。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    相关资源
    最近更新 更多