opencvsimplecv

Editing a code: how to access my webcame instead of a photo


So I am having a prewritten code for finding the brightest pixel in an Image - the code has commands in it which load a picture. What I need is to find the brightest pixel in a live video made with my webcame. So what I need to do now is to delete the lines which want to load the picture, and add lines to access the camera. I have been trying to do so for hours now, but I am always getting error messages, does anybody have an idea how to solve that? This is the code I need to edit:

# import the necessary packages
import numpy as np
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-r", "--radius", type = int,
    help = "radius of Gaussian blur; must be odd")
args = vars(ap.parse_args())

# load the image and convert it to grayscale
image = cv2.imread(args["image"])
orig = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# perform a naive attempt to find the (x, y) coordinates of
# the area of the image with the largest intensity value
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)
cv2.circle(image, maxLoc, 5, (255, 0, 0), 2)

# display the results of the naive attempt
cv2.imshow("Naive", image)

# apply a Gaussian blur to the image then find the brightest
# region
gray = cv2.GaussianBlur(gray, (args["radius"], args["radius"]), 0)
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)
image = orig.copy()
cv2.circle(image, maxLoc, args["radius"], (255, 0, 0), 2)

# display the results of our newly improved method
cv2.imshow("Robust", image)
cv2.waitKey(0)

I want to delete the whole '# load the image and convert it to grayscale' block and want to add the following lines:

Import SimpleCV
cam = SimpleCV.Camera()
img = cam.getImage().flipHorizontal().toGray()
img.show()

Does anybody know how I can edit the code without getting new error messages?


Solution

  • Accessing a webcam stream in opencv is very easy.

    To do so, write something like cap = cv2.VideoCapture(XXX) where XXX is the path to the file with the video, an ip address for an ip camera or 0 for the default computer webcam.

    Once this stream is acquired, you can iterate through the images like so:

    while(True):
        didReturnImage, image = cap.read()
        if not didReturnImage:
            #The VideoCapture did not provide an image. 
            #Assuming this to mean that there are no more left 
            #in the video, we leave the loop.
            break
        else:
            #image is now available for use as a regular image
    

    Just place your code in this loop, starting from orig = image.copy() in the above loop.

    (Note: You may want to change the line cv2.waitKey(0) to cv2.waitKey(1) because the first will keep the image on screen forever, while the second will keep it on until the next image is shown.)