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

Faster way to loop through each pixel in an image in python?

需要 运行 遍历 python 中的图像,并主要计算特定边界内所有可接受像素的平均位置。图像是黑白的。可接受像素的值为 255,不可接受像素的值为零。该图像类似于 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() 将 return 条件为真的索引数组,我们可以对其取平均值(加 1 以匹配您的索引)并转换为整数:

if np.any(mask == 255):
    y, x = [int(np.mean(indices + 1)) for indices in np.where(mask == 255)]

我认为您正在寻找白色像素的质心,OpenCV 会很快为您找到:

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image as greyscale
im = cv2.imread('star.png')

# Make greyscale version
grey = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

# Ensure binary
_, grey = cv2.threshold(grey,127,255,0)

# Calculate moments
M = cv2.moments(grey)

# Calculate x,y coordinates of centre
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# Mark centroid with circle, and tell user
cv2.circle(im, (cX, cY), 10, (0, 0, 255), -1)
print(f'Centroid at location: {cX},{cY}')

# Save output file
cv2.imwrite('result.png', im)

示例输出

Centroid at location: 1224,344

上面的 1692x816 图像需要 381 微秒,如果我将图像大小调整为您的图像尺寸,则增加到 1.38 毫秒...我称之为 10,800 倍加速