Machine Vision Technology Development
Experiment 1 - Opening USB Camera
cd OPENCV# Open OPENCV packagesudo python3 ./camera_display.py# Run py file
Terminal displays:

At this time, the Linux system will display the camera's real-time video. We need to test the keys under the window focus, the effect is as follows:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Camera capture program
Function: Open camera and display real-time video, supports multiple functions
"""
import cv2
import numpy as np
import sys
import os
import time
import argparse
from datetime import datetime
def main():
"""
Main function: Open camera and display real-time video
"""
# Parse command line arguments
parser = argparse.ArgumentParser(description='Camera real-time display program')
parser.add_argument('--width', type=int, default=1280, help='Display window width')
parser.add_argument('--height', type=int, default=720, help='Display window height')
args = parser.parse_args()
# Open default camera (usually 0, if multiple cameras try 1, 2, etc.)
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if not cap.isOpened():
print("Error: Unable to open camera")
sys.exit(1)
# Set camera resolution
cap.set(cv2.CAP_PROP_FRAME_WIDTH, args.width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, args.height)
# Create a resizable window
cv2.namedWindow('Camera', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Camera', args.width, args.height)
print("Camera opened successfully")
print(f"Window size set to: {args.width}x{args.height}")
print("Key instructions:")
print("- 'q': Exit program")
print("- 'g': Toggle grayscale/color mode")
print("- 'b': Apply blur effect")
print("- 'e': Apply edge detection")
print("- 'n': Restore normal mode")
print("- 's': Save current frame as image")
print("- '+': Increase window size")
print("- '-': Decrease window size")
# Default settings
gray_mode = False
blur_mode = False
edge_mode = False
window_width = args.width
window_height = args.height
# Create directory for saving images
save_dir = "captured_images"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# Loop to read camera frames
while True:
# Read a frame
ret, frame = cap.read()
# If failed to read, exit loop
if not ret:
print("Error: Unable to read camera frame")
break
# Process image
if gray_mode:
# Convert to grayscale
processed_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Convert back to three channels for text display
display_frame = cv2.cvtColor(processed_frame, cv2.COLOR_GRAY2BGR)
mode_text = "Gray Mode"
else:
processed_frame = frame.copy()
display_frame = processed_frame
mode_text = "Color Mode"
# Apply additional effects
if blur_mode:
processed_frame = cv2.GaussianBlur(processed_frame, (15, 15), 0)
display_frame = processed_frame
mode_text += " + Blur"
if edge_mode and gray_mode:
# Edge detection requires grayscale image
processed_frame = cv2.Canny(processed_frame, 100, 200)
# Convert back to three channels for text display
display_frame = cv2.cvtColor(processed_frame, cv2.COLOR_GRAY2BGR)
mode_text += " + Edge"
elif edge_mode:
# If not grayscale mode, convert to grayscale first then do edge detection
edges = cv2.Canny(cv2.cvtColor(processed_frame, cv2.COLOR_BGR2GRAY), 100, 200)
# Overlay edges on original image
display_frame = processed_frame.copy()
display_frame[edges > 0] = [0, 255, 255] # Yellow edges
mode_text += " + Edge"
# Add mode text
cv2.putText(display_frame, mode_text, (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
# Display image
cv2.imshow('Camera', display_frame)
# Wait for key press, exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
print("User exited program")
break
elif key == ord('g'):
# Toggle grayscale/color mode
gray_mode = not gray_mode
print("Switched to", "grayscale mode" if gray_mode else "color mode")
elif key == ord('b'):
# Toggle blur effect
blur_mode = not blur_mode
print("Blur effect:", "on" if blur_mode else "off")
elif key == ord('e'):
# Toggle edge detection
edge_mode = not edge_mode
print("Edge detection:", "on" if edge_mode else "off")
elif key == ord('n'):
# Restore normal mode
gray_mode = False
blur_mode = False
edge_mode = False
print("Restored to normal mode")
elif key == ord('s'):
# Save current frame
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(save_dir, f"capture_{timestamp}.jpg")
cv2.imwrite(filename, frame)
print(f"Image saved: {filename}")
# Release camera resources
cap.release()
# Close all OpenCV windows
cv2.destroyAllWindows()
print("Program exited")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"Program error: {e}")
sys.exit(1)