如何从picamera(python,opencv)抽象数组中的图像

时间:2016-11-16 08:33:42

标签: python arrays opencv raspberry-pi

我是picamera的新手。现在我想通过相机检测不复杂的运动,我使用cv2.absdiff()。但是,我得到的数组(image1,image2)是相同的。如何获取不同的抽象数组或获取数组中的元素(图像)? 这是我的代码:

import sys
sys.path.append('/usr/local/lib/python2.7/site-packages')
from picamera.array import PiRGBArray
from picamara import PiCamera
import cv2
import time
import time
import numpy as np

camera = PiCamera()
camera.resolution = (640,480)
camera.framerate = 32
rawCapture = PiRGBArray(camera,size=(640,480))

time.sleep(0.1)

for frame in camera.capture_continuous(rawCapture,format="bgr",use_video_port=True):

    image1 = frame.array
    gray1 = cv2.cvtColor(image1,cv2.COLOR_BGR2GRAY)
    cv2.waitKey(33)
    image2 = frame.array
    gray2 = cv2.cvtColor(image2,cv2.COLOR_BGR2GRAY)

    diff = cv2.absdiff(gray1,gray2)
    cv2.imshow("DIFF",diff)

    key = cv2.waitKey(33)&0xFF
    rawCapture.truncate(0)
    if key == ord("q"):
        break

1 个答案:

答案 0 :(得分:1)

您的脚本正在尝试将同一帧与自身进行比较,这显然不会显示任何差异。

一种方法是在开始循环之前采用单个初始帧,然后将任何后续帧与之比较,如下所示:

import sys
#sys.path.append('/usr/local/lib/python2.7/site-packages')
from picamera.array import PiRGBArray
from picamara import PiCamera
import cv2
import time
import time
import numpy as np

camera = PiCamera()
camera.resolution = (640,480)
camera.framerate = 32
rawCapture = PiRGBArray(camera,size=(640,480))
time.sleep(0.1)
initial_frame = camera.capture(rawCapture, format="bgr", use_video_port=True):

for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    cv2.waitKey(33)
    image2 = frame.array
    gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)

    diff = cv2.absdiff(initial_frame, gray)
    cv2.imshow("DIFF", diff)

    key = cv2.waitKey(33) & 0xFF
    rawCapture.truncate(0)

    if key == ord("q"):
        break 

您可以进一步增强它以定期更新初始框架,以应对背景的任何长期更改。