Domanda

i've been trying to display the camera feed from my laptops web cam in grayscale and i've done it using the following code:

    import cv2
    import numpy as np
    clicked = False
    def onMouse(event, x, y, flags, param):
        global clicked
        if event == cv2.cv.CV_EVENT_LBUTTONUP:
            clicked = True

    cv2.namedWindow('image capture', cv2.WINDOW_NORMAL)
    cv2.setMouseCallback('image capture', onMouse)
    #initialize the camera object with VideoCapture
    camera = cv2.VideoCapture(0)
    sucess, frame = camera.read()
    cv2.imwrite('snapshot.png', frame)
    gray = cv2.imread('snapshot.png', cv2.IMREAD_GRAYSCALE)
    while sucess and cv2.waitKey(1) == -1 and not clicked:
        cv2.imwrite('snapshot.png', frame)
        gray = cv2.imread('snapshot.png', cv2.IMREAD_GRAYSCALE)
        cv2.imshow('image capture', gray)
        sucess, frame = camera.read()

    cv2.imwrite('snapshot.png', frame)
    print 'photo taken press any key to exit'
    cv2.waitKey()
    cv2.destroyAllWindows()

Here what i've done is saved the frame in 'snapshot.png' and again reloaded it in grayscale and display that grayscale image. Is there any method to directly read the camera frame in grayscale rather than going through all this mess. Thanks in advance.

È stato utile?

Soluzione

wow, what a mess ;)

you simply want:

gray = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY )

Altri suggerimenti

In the latest version of opencv, the cvtColor expects it's scr to be not None and therefore gives 215-assertion error. This is basically like a scenario where you have to use a catch block and try to handle exceptions.

Code to overcome this problem:

while True:
    
    ret, frame = cap.read()

    if frame.any():
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    cv2.imshow('frame', gray)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top