python - 如何使用 openCV 在 Python 中提高视频播放速度

标签 python performance opencv video-capture

我正在编写一个程序,在遇到栏杆的第一个像素的视频上画一条线,我的问题是视频播放缓慢。

enter image description here 屏幕截图以供引用视频的外观。拍视频的时候镜头靠得更近了,但是因为速度慢,我得等几分钟才能看到变化,但是拍摄的时候,镜头每隔几秒就移动一次。

我假设问题是 for 循环在视频的每一帧上运行,但我不确定。

我可以实现什么解决方案来加速我的程序?

import cv2

cap = cv2.VideoCapture('video.mp4')

while(cap.isOpened()):

    ret, frame = cap.read()
    canny = cv2.Canny(frame, 85, 255)
    height, width = canny.shape

    first_black_array = []

    for x in range(width):
        first_black_pixel_found = 0
        for y in range(height):
            if first_black_pixel_found == 0:
                if canny[y,x] == 255:
                    first_black_array.append(height - y)
                    first_black_pixel_found = 1
                    cv2.line(frame,(x,y),(x,y),(0,255,0),1)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

谢谢!

最佳答案

这就是问题...

for x in range(width):
    for y in range(height):
         if canny[y,x] == 255:

Numpy.argmax 是解决方案...

for x in range(width-1):
    # Slice the relevant column from the image
    # The image 'column' is a tall skinny image, only 1px thick
    column = np.array(canny[:,x:x+1])
    # Use numpy to find the first non-zero value
    railPoint = np.argmax(column)

完整代码:

import cv2, numpy as np, time
# Get start time
start = time.time()
# Read in the image
img = cv2.imread('/home/stephen/Desktop/rail.jpg')[40:,10:-10]
# Canny filter
canny = cv2.Canny(img, 85, 255)
# Get height and width
height, width = canny.shape
# Create list to store rail points
railPoints = []
# Iterate though each column in the image
for position in range(width-1):
    # Slice the relevant column from the image
    # The image 'column' is a tall skinny image, only 1px thick
    column = np.array(canny[:,position:position+1])
    # Use numpy to find the first non-zero value
    railPoint = np.argmax(column)
    # Add the railPoint to the list of rail points
    railPoints.append(railPoint)
    # Draw a circle on the image
    cv2.circle(img, (position, railPoint), 1, (123,234,123), 2)
cv2.imshow('img', img)                      
k = cv2.waitKey(1)
cv2.destroyAllWindows()
print(time.time() - start)

我使用 Numpy 的解决方案耗时 6 毫秒,而您的解决方案耗时 266 毫秒。 rail output

关于python - 如何使用 openCV 在 Python 中提高视频播放速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167231/

相关文章:

python - 如何递归检查python列表的所有组合

PHP : What is the benefit of spl_autoload_register? 包含的性能

opencv - bash 中的人脸检测 : Simply return number of faces found

OpenCV3.0 - 模块没有属性 SIFT

时间:2019-04-10 标签:c#additional dependencies-opencvsharp

python - MySQL Python LIKE 通配符

python - python 中是否有与 MATLAB 函数 bsxfun 等效的函数?

python - 如何使用 pydantic 生成严格的 json 模式?

java - 具有队列基​​本功能的最快 Java 集合是什么?

javascript - js 内存组织 - 闭包与对象?