Ask Your Question
0

Take a snapshot with the webcam in python?

asked 2018-04-16 11:16:27 -0600

Philia gravatar image

So I am trying a write a program to detect objects using openCV libraries using Python.

The code to detect object is somewhat satisfactory. When I run the code, it opens the webcam and when the object the system has been trained to detect is visible with the cam it detects it and draws a rectangle and writes what the object is. So far so good. However I want the program to take a snap for the first time it detects something. And close the webcam and shows the pic instead. Here's the code I have written so far:

import cv2
import numpy as np


cascade1 = cv2.CascadeClassifier('xcascade.xml')
cascade2 = cv2.CascadeClassifier('ycascade.xml')

def TakeSnapAndSave():
    cap = cv2.VideoCapture(0)

    num = 0
    while num<1000:
        ret, img = cap.read()
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

        object1 = xcascade.detectMultiScale(gray, 10, 10)
        for(x,y,w,h) in object1:
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.rectangle(img,(x,y), (x+w,y+h),(255,255,0),5)
            cv2.putText(img, 'Something',(x,y-40), font, 1.5, (255,255,0),5, cv2.LINE_AA)
            object2 = ycascade.detectMultiScale(gray, 15, 15)
            for(x,y,w,h) in object2:
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.rectangle(img,(x,y), (x+w,y+h),(0,255,255),5)
                cv2.putText(img, 'Something Else',(x+100,y+80), font, 0.8, (0,0,255),2, cv2.LINE_AA)        


        cv2.imwrite('opencv'+str(num)+'.jpg',img)
        num = num+1
    cap.release()
    cv2.destroyAllWindows()

The code keeps taking snapshots without doing any detection.....

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-04-16 11:33:50 -0600

berak gravatar image

updated 2018-04-16 12:08:06 -0600

it looks, like you're simply don't know, what you're doing.

indenting the

    cv2.imwrite('opencv'+str(num)+'.jpg',img)
    num = num+1

code once more, (so it's inside the for(x,y,w,h) in object1: block) would probably do exactly, what you wanted. why didn't you find out on your own ?

edit flag offensive delete link more

Comments

Because I am a noob....thanks....I will try it out, when I get back to my PC

Philia gravatar imagePhilia ( 2018-04-16 12:26:13 -0600 )edit

It somewhat worked.....but it keeps taking snaps. I want it to take one picture and stop. Also it doesn't show me the webcam feed either. I want the program to show me the detection in webcam. Once it detects the objects in the webcam it should take only one snap, close the webcam and view that image.....

Philia gravatar imagePhilia ( 2018-04-17 09:06:20 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-04-16 11:16:27 -0600

Seen: 6,534 times

Last updated: Apr 16 '18