Example program - take a photo with a webcam, display that photo to the operator using a notify() popup

I whipped up this example program in advance of a webinar I’m giving on Friday this week on using Python inside robot programs. I see a number of possible uses for having the robot take photos and store them on the file system. This example is really simple and is only meant to give people a jumping off point.

1 Like

One my first run through of this program the camera was not working (which I had not verified ahead of time) and PP gave me an error that was tricky to understand.

Error executing program: File “Webcam_Rogge.py”, line 30:
OpenCV(4.2.0) …/modules/imgcodecs/src/loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function ‘imwrite’

This could be addressed by checking for the presence of a camera before trying to take a picture and save it or otherwise giving a human readable error message something to the effect of “Camera not found”

1 Like

@dfroeschner - welcome to the Tormach user forums!

Thanks for the feedback on that example program. I completely agree - a check to ensure there’s a camera connected and functioning would save the next person who tries this code out a lot of hassle. I’ll make that code change and push it up to the repository ASAP. Thank you!

1 Like

The aforementioned exception is propagated from the underlying C++ OpenCV code. You can catch them as you would usually do in Python, for example

    while (result):
        try:
            ret, frame = videoCaptureObject.read()
            cv2.imwrite(filename, frame)
            result = False
        except Exception as e:
            notify(f"Exception: {e}", error=True)

(Not exactly useful, but you get the gist. The action and meaning of the exception will be always on the programmer.)

You can actually check the camera connection after creation of the VideoCaptureObject with the isOpened method. Pull request at Check the camera is connected by cerna · Pull Request #2 · tormach/example_robot_programs · GitHub does exactly that.

@Cerna - thanks for that pull request. I merged it, and the example up on github should now warn users when a camera isn’t found.

@dfroeschner thanks for the suggestion!

@Rogge and @Cerna Fabulous work. I ran it on the robot and got a popup and error log entry for "Cannot access the camera on index ‘0’. Please, check the dev/video0 device. "

I had this working a few days ago, but now I am getting an error


I have cheese installed onto my machine to check camera connection, and the camera feed is popping up… now I am scratching my head!

@sorgule Replying to myself- I’m not sure how “scientific” this is, but I turned off the machine and turned it back on and the problem fixed itself.

@sorgule I’m glad it’s now working for you. If the problem happens again or you find a way to reproduce it please let me know.

Check out an example of this in action:

1 Like