需要在 python 中运行图像并本质上计算特定边界内所有可接受像素的平均位置。图像是黑白的。可接受的像素的值为 255, Not Acceptable 像素的值为 0。该图像类似于 2592x1944,运行可能需要 15 秒。这需要循环几次。有没有更快的方法来做到这一点?
goodcount = 0
sumx=0
sumy=0
xindex=0
yindex=0
for row in mask:
yindex+=1
xindex=0
for n in row:
xindex+=1
if n == 255:
goodcount += 1
sumx += xindex
sumy += yindex
if goodcount != 0:
y = int(sumy / goodcount)
x = int(sumx / goodcount)
最佳答案
np.where()
将返回条件为 true 的索引数组,我们可以对其求平均值(加 1 以匹配您的索引)并转换为整数:
if np.any(mask == 255):
y, x = [int(np.mean(indices + 1)) for indices in np.where(mask == 255)]
关于python - 在Python中循环遍历图像中每个像素的更快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72190004/