此程序的高效 for 循环

问题描述 投票:0回答:1

我正在编写一个程序来逐帧分析视频。该程序应该计算随时间变化的物体的高度。我利用了对象顶部是白色的事实,因此我会打印出白色像素的位置来找到顶部的位置,并从那里测量对象的高度。我能够编写这样的程序,但是迭代每一帧(每个视频大约 10,000 帧)的 for 循环落后于整个程序。计算出每一帧中物体的高度几乎需要一天的时间。我的问题是,有没有更好、更有效的方法来解决这个问题?

capture = cv2.VideoCapture("/Users/beadpile/Desktop/aman/bpile.mp4")   
_, frame = capture.read()
MovieBase = MovieName
angles=[]
y_base = 247
x_center = 569
x_edgeL = 51
x_edgeR = 1087
for i in range(0,1000):
    capture.set(cv2.CAP_PROP_POS_FRAMES, i)
    _, frame = capture.read()
    white = [255,255,255]
    # Get X and Y coordinates of all white color pixels
    X,Y = np.where(np.all(frame==white,axis=2))
    XX=list(X)
    YY=list(Y)
    xpoints = np.array(X)
    ypoints = np.array(Y)
    test_list=list(zip(xpoints,ypoints))
    #get x,y coordinate of the white pixels found at the top     of the object
    subcoords = [(x, y) for x, y in test_list if y==min(YY)]
    s=[]
    for j in subcoords:
    s.append(j[0])
    #find average value of the x coordinate of the values     coordinates from subcoordds
    xax=sum(s)/len(subcoords)
    slope=(y_base-min(YY))/(xax-x_edgeL)
#gets angle that extends from one point to the top of the object
    aangle=math.degrees(math.atan(slope))
    angles.append(aangle)
print(angles)
python-3.x for-loop nested-loops video-capture
1个回答
0
投票

您假设堆中只有白色像素,但堆外还有其他白色像素。你必须先清理这些像素。

清理这些像素后

此代码显示了使用 numpy 清理后的图像中堆的高度和宽度

import numpy as np
import requests
import cv2

# Download the image from stackoverflow
#url = "https://i.stack.imgur.com/y6mbR.jpg" # Original image
url = "https://i.stack.imgur.com/xLG0M.jpg" # Cleaned image
response = requests.get(url, stream=True)
img_array = np.array(bytearray(response.raw.read()), dtype=np.uint8)
img = cv2.imdecode(img_array, -1)

# Find white pixels
white = np.array([255, 255, 255], dtype=np.uint8)
white_pixels = np.all(img == white, axis=-1)
white_columns = white_pixels.max(axis=0)
white_rows = white_pixels.max(axis=1)

white_rows_indexes = np.where(white_rows == True)[0]
print(f"height of pile = {white_rows_indexes[-1]-white_rows_indexes[0]+1}")

white_column_indexes = np.where(white_columns == True)[0]
print(f"Width of pile = {white_column_indexes[-1]-white_column_indexes[0]+1}")

cv2.imshow('Image', white_pixels.astype(np.uint8)*255)
cv2.waitKey(0)
cv2.destroyAllWindows()
© www.soinside.com 2019 - 2024. All rights reserved.