SingleImage (saving as PNG)
This sample captures one image from the INFINICAM GbE-2 and saves it as a PNG image file, using OpenCV. PNG files open as they are in ordinary image viewers, such as the Windows Photos app.
-
Enter and save the program
Save the following code as
single_image_png.pyinC:\infinicam_projects\python.import cv2from pypuclib import CameraFactory, PUCExceptionprint("Connecting to the camera...")try:# Connect to the GbE-2 at this IP addresscam = CameraFactory().create(ip="192.168.0.10")except PUCException as e:print("Error: could not connect to the camera.", e)raise SystemExit(1)try:# Receive one frame of compressed data and decode it into an image (a NumPy array)data = cam.grab()image = cam.decoder().decode(data)finally:cam.close()print("Image size:", image.shape[1], "x", image.shape[0])# Save as PNG with OpenCV (images from a color camera can be saved as they are)filename = "captured_image.png"if cv2.imwrite(filename, image):print("Saved:", filename)else:print("Error: could not save the image.") -
Run it
Run the following 2 lines, one at a time, in Command Prompt (or PowerShell).
Terminal window cd C:\infinicam_projects\pythonTerminal window python single_image_png.pyIf you see the following and
captured_image.pngappears inC:\infinicam_projects\python, it worked. Double-click it in File Explorer to open it in the Photos app.Connecting to the camera...Image size: 800 x 600Saved: captured_image.png
How the program works
Section titled “How the program works”1. Import OpenCV
Section titled “1. Import OpenCV”import cv2In Python, OpenCV is imported under the name cv2. Note that this is different from the name you install it under (opencv-python).
2. Save as PNG
Section titled “2. Save as PNG”cv2.imwrite(filename, image)Just pass cv2.imwrite() a file name and an image (a NumPy array) to save it.
- The format is decided by the file name extension. Name it
captured_image.jpgto save JPEG, orcaptured_image.bmpto save BMP. - It returns
Trueif the file was saved andFalseif not, so the program checks the result withif. - Images from a color camera (height × width × 3 colors arrays) can also be saved as they are.
3. Saving with Pillow
Section titled “3. Saving with Pillow”You can also save with Pillow instead of OpenCV. Pillow is an image library installed along with the others in Setting up a Python development environment.
from PIL import Image
Image.fromarray(image).save("captured_image_pil.png")Image.fromarray() converts the NumPy array into a Pillow image, and save() saves it.
