簡體   English   中英

在 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()將返回 arrays 個條件為真的索引,我們可以對其進行平均(加 1 以匹配您的索引)並轉換為 integer:

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)

在此處輸入圖像描述

樣品 Output

Centroid at location: 1224,344

在上面的 1692x816 圖像上需要 381 微秒,如果我將圖像大小調整為圖像的尺寸,則上升到 1.38 毫秒......我稱之為 10,800 倍加速

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM