python - 在Python中循环遍历图像中每个像素的更快方法?

标签 python arrays image numpy

需要在 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/

相关文章:

javascript - Array.push throw TypeError for array.push is not a function

python - 如何在不迭代的情况下基于成对的开始/结束索引定义 numpy 数组的多个切片?

ruby-on-rails - 为什么回形针插值不起作用?

image - FFmpeg 前 2 秒视频不显示

ruby-on-rails - Ruby on Rails 5.2 - 具有主动存储的背景图像

python - 如何使用 SAS 对存储队列的 Azure REST API 进行身份验证?

C++:处理不同大小数组的函数

python - Django 根据值从查询集中获取不同的结果

python - 当从数据存储中删除条目时,其相应的搜索文档是否也会被删除?

Python 将文本分配给新变量