我試圖找到最好的方法來檢索大于某個閾值的像素值的總和。例如,如果我的閾值為 253,我得到 10 個像素為 254,另外 10 個像素為 255,我希望得到10*254 10*255 = 5090- 超過閾值的像素的總強度。
我找到了一種方法np.histogram:
import cv2, time
import numpy as np
threshold = 1
deltaImg = cv2.imread('image.jpg')
t0=time.time()
histogram = np.histogram(deltaImg,256-threshold,[threshold,256])
histoSum = sum(histogram[0]*histogram[1][:-1])
print(histoSum)
print("time = %.2f ms" % ((time.time()-t0)*1000))
這個作品,我得到的像素的總和衣被合計了比選定的閾值更大。但是,我不確定這是最好/最快的方法。顯然,閾值越大,動作就越快。
有沒有人知道如何使用更快的演算法獲得正確的結果?
uj5u.com熱心網友回復:
干得好:
import numpy as np
image = np.random.randint(0,256,(10,10))
threshold = 1
res = np.sum(image[image > threshold])
這個操作:
%%timeit
res = np.sum(image[image >=threshold])
需要5.43 μs ± 137 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each).
uj5u.com熱心網友回復:
雖然 OP 的方法從根本上是不準確的,但其基本思想仍然可以用來制作一種對整數陣列(例如灰度影像)有效的方法:
def sum_gt_hist(arr, threshold):
values = np.arange(threshold, np.max(arr) 1)
hist, edges = np.histogram(arr, values 0.5)
return sum(values[1:] * hist)
然而,這并不理想,因為它比應有的更復雜(np.histogram()是一個相對復雜的函式,它計算的中間資訊比所需的要多得多)并且僅適用于整數值。

import cv2
import numpy as np
# read image
img = cv2.imread('ramp.png')
print(img.shape)
# convert img to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold to zero below threshold, but keep values above threshold
# note: to count all values of 254 and 255, use threshold at 253
thresh = cv2.threshold(gray, 253, 255, cv2.THRESH_TOZERO)[1]
# sum non-zero pixel values
sum = np.sum(thresh[thresh != 0])
print("actual count:", sum)
# compute the expected count
sum2 = 100*254 100*255
print("computed count:", sum2)
# show results
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
結果:
actual count: 50900
computed count: 50900
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340888.html
上一篇:為什么python不給我關閉openCV視窗的選項?
下一篇:CUDA內核的奇怪行為
