简体   繁体   English

图像处理的二进制阈值

[英]Binary Thresholding for Image processing

I am new to python and I learning image processing.我是 python 的新手,我正在学习图像处理。 A very basic concept of Thresholding is causing some confusion.阈值的一个非常基本的概念引起了一些混乱。 I understand that it can be implemented as:我知道它可以实现为:

if AvgPix > T:
   pix  = 255
else:
   pix  = 0

I found this code to calculate the threshold value for the image-我找到了这段代码来计算图像的阈值-

for eachrow in imagearray:
        for eachpix in eachrow:
            avg = reduce(lambda x,y: x + y ,eachpix[:3]) / len(eachpix[:3])
            balanceAr.append(avg)
threshold  = reduce(lambda x,y: x + y ,balanceAr) / len(balanceAr) 

I found that when eachpix = array([239, 228, 176, 255], dtype=uint8) , the avg getting calculated is 131 as per this code.我发现当eachpix = array([239, 228, 176, 255], dtype=uint8)时,根据此代码计算的平均值为 131。 Shouldn't it be = (239+228+176)/3 = 214.3不应该是 = (239+228+176)/3 = 214.3

Please help me in understanding this.请帮助我理解这一点。 If I am missing something!如果我错过了什么!

I wasn't able to reproduce the problem:我无法重现该问题:

from functools import reduce

pix = [239, 228, 176, 255]

imagearray = [
    [pix, pix, pix],
    [pix, pix, pix],
    [pix, pix, pix]
]

balanceAr = []

for eachrow in imagearray: 
    for eachpix in eachrow: 
        avg = reduce(lambda x,y: x + y, eachpix[:3]) / len(eachpix[:3])
        balanceAr.append(avg) 

threshold = reduce(lambda x,y: x + y, balanceAr) / len(balanceAr)

print(threshold) # 214.3

And by the way, you can get an average of a list without reduce() :顺便说一句,你可以在没有reduce()的情况下得到一个列表的平均值:

avg = sum(my_list) / len(my_list)

So it can be boiled down to this:所以可以归结为:

pix = [239, 228, 176, 255]

imagearray = [
    [pix, pix, pix],
    [pix, pix, pix],
    [pix, pix, pix]
]

def avg(lst):
    return sum(lst) / len(lst)

threshold = avg( [avg([avg(px[:3]) for px in row]) for row in imagearray] ) 

print(threshold) # 214.3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM