杰瑞科技汇

python opencv write

Of course! Writing images and videos with OpenCV in Python is a fundamental task. Here’s a comprehensive guide covering the most common use cases, from saving a simple image to writing a video file.

python opencv write-图1
(图片来源网络,侵删)

Writing an Image

This is the most straightforward task. You use the cv2.imwrite() function.

The Basic Function

cv2.imwrite(filename, image)
  • filename: A string containing the path and name of the output file. You must include the extension (e.g., .png, .jpg).
  • image: The NumPy array representing the image you want to save.
  • Returns: True if the image was successfully saved, False otherwise.

Example 1: Saving an Image from a NumPy Array

Let's create a blank image and save it as a PNG file.

import cv2
import numpy as np
# Create a blank image (a 300x300 black image)
# Shape: (height, width, channels)
blank_image = np.zeros((300, 300, 3), dtype=np.uint8)
# Draw a red rectangle on the blank image
cv2.rectangle(blank_image, (50, 50), (250, 250), (0, 0, 255), -1)
# Save the image
# The first argument is the filename, the second is the image array
success = cv2.imwrite('output_image.png', blank_image)
if success:
    print("Image saved successfully as 'output_image.png'")
else:
    print("Error saving the image.")

Example 2: Saving a Webcam Frame

This is a very common use case: capture a frame from a camera and save it.

import cv2
# Initialize the webcam (0 is usually the default webcam)
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
    print("Error: Could not open video device.")
    exit()
# Read a single frame from the webcam
ret, frame = cap.read()
if ret:
    # Save the captured frame
    cv2.imwrite('webcam_capture.jpg', frame)
    print("Image saved successfully as 'webcam_capture.jpg'")
# Release the webcam and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()

Writing a Video

Writing a video is more complex than writing an image. You need to create a VideoWriter object, write frames to it one by one, and then release it.

python opencv write-图2
(图片来源网络,侵删)

The Key Components

  1. cv2.VideoWriter(): This object handles the video file creation and writing process.
  2. writer.write(frame): This method appends a new frame to the video.

cv2.VideoWriter() Constructor

cv2.VideoWriter(filename, fourcc, fps, frameSize[, isColor])
  • filename: The path and name of the output video file (e.g., 'output_video.avi').
  • fourcc: A 4-byte code that specifies the video codec. This is crucial and depends on the file format.
    • cv2.VideoWriter_fourcc(*'XVID'): Good for .avi files.
    • cv2.VideoWriter_fourcc(*'MP4V'): Good for .mp4 files.
    • cv2.VideoWriter_fourcc(*'MJPG'): Another option for .avi.
    • cv2.VideoWriter_fourcc(*'avc1'): For H.264 in .mp4 (can be tricky, might require ffmpeg).
  • fps: The frames per second for the output video (e.g., 0).
  • frameSize: A tuple (width, height) representing the size of the video frames. This must match the size of the frames you write.
  • isColor: A boolean flag. If True, the video is in color. If False, it's in grayscale. The default is True.

Example 3: Writing a Video from a Webcam Feed

This example captures a live feed from your webcam and saves it as an MP4 file.

import cv2
# --- 1. Setup Video Capture and Video Writer ---
# Initialize the webcam
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
    print("Error: Could not open video device.")
    exit()
# Get the properties of the video stream
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = 20.0  # Frames per second for the output video
# Define the codec and create a VideoWriter object
# For an MP4 file, 'MP4V' is a common codec.
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output_video.mp4', fourcc, fps, (frame_width, frame_height))
print("Recording started. Press 'q' to stop and save.")
# --- 2. Read Frames and Write to Video File ---
while True:
    # Read a frame from the webcam
    ret, frame = cap.read()
    if not ret:
        print("Error: Failed to capture frame.")
        break
    # Write the frame to the output video file
    out.write(frame)
    # Display the frame (optional)
    cv2.imshow('Recording', frame)
    # Exit the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# --- 3. Release Everything ---
# Release the VideoWriter and VideoCapture objects
out.release()
cap.release()
# Close all OpenCV windows
cv2.destroyAllWindows()
print("Video saved as 'output_video.mp4'")

Saving an Image with Specific Quality (JPEG)

When saving a JPEG image, you can control the quality/compression level. This is done with an optional third parameter in cv2.imwrite().

  • The parameter is an integer from 0 (worst quality, smallest file) to 100 (best quality, largest file).
  • The default quality is 95.
import cv2
import numpy as np
# Create a sample image
image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
# Save with different quality levels
cv2.imwrite('high_quality.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 100])
cv2.imwrite('medium_quality.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 50])
cv2.imwrite('low_quality.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 10])
print("JPEG images saved with different quality levels.")

Important Tips and Common Issues

  1. File Extensions Matter: Always use the correct file extension (.jpg, .png, .mp4, .avi). It helps OpenCV determine the format.
  2. Codec Compatibility: If you can't open your saved video, the most likely culprit is the fourcc codec. Not all codecs work on all systems. XVID for .avi and MP4V for .mp4 are generally safe bets.
  3. Frame Size Consistency: When writing a video, the frameSize you provide to VideoWriter must exactly match the dimensions of the frames you pass to writer.write(). A common mistake is to resize frames inside the loop but forget to update the frameSize for the VideoWriter.
  4. Release Resources: Always remember to release() your VideoCapture and VideoWriter objects. Failure to do so can lead to resource leaks and files that are not properly written.
  5. Check Return Values: Always check the boolean return value of cap.read() and cv2.imwrite() to ensure operations are successful. This is good practice for debugging.
python opencv write-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇