Superimposing image over webcam feed using OpenCV 2.4.7.0 in Python 2.7

Question:

I am trying to superimpose an image over a camera feed in python. I can get an image to superimpose over another image, but when I apply the same thing to my camera feed it doesn’t work. Here’s my code so far:

#!/usr/bin/python

import cv2
import time

cv2.cv.NamedWindow("Hawk Eye", 1)

capture = cv2.cv.CaptureFromCAM(0)
cv2.cv.SetCaptureProperty(capture, cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 800)
cv2.cv.SetCaptureProperty(capture, cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 600)

x_offset=y_offset=50
arrows = cv2.imread("arrows.png")

while True:
    webcam=cv2.cv.QueryFrame(capture)
    #webcam[y_offset:y_offset+arrows.shape[0], x_offset:x_offset+arrows.shape[1]]=arrows
    cv2.cv.ShowImage("Hawk Eye", webcam)
    if cv2.cv.WaitKey(10) == 27:
        break
cv2.cv.DestroyAllWindows()

If I uncomment:

img[y_offset:y_offset+arrows.shape[0], x_offset:x_offset+arrows.shape[1]]=arrows

the line that imposes the image, it shows just the camera feed, but when I add it in my loop it stops working. Thanks!

Asked By: user3121062

||

Answers:

This works OK using the cv2 API:

import cv2
import time

cv2.namedWindow("Hawk Eye", 1)

capture = cv2.VideoCapture(0)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 800)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 600)

x_offset=y_offset=50
arrows = cv2.imread("hawk.png")

while True:
    ret, webcam = capture.read()
    if ret:
        webcam[y_offset:y_offset+arrows.shape[0], x_offset:x_offset+arrows.shape[1]]=arrows
        cv2.imshow("Hawk Eye", webcam)
        if cv2.waitKey(10) == 27:
            break
cv2.destroyAllWindows()
Answered By: b_m
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.