2.8 Python example code

mseokq23·2025년 1월 6일

Palatable Python

목록 보기
11/11

gray

import cv2

# color image loading: cv2.IMREAD_COLOR
image = cv2.imread("luffy.jpg", cv2.IMREAD_GRAYSCALE)

# check image load
if image is None:
    print("Image loading failed, Please check the path!")
else:
    print("Image Shape:", image.shape)  # gray: (512, 512), color: (512, 512, 3)
    print("Image:\n", image)

# display image
cv2.imshow("Loaded Image", image)
cv2.waitKey(0)  # press any key, program will end
cv2.destroyAllWindows()

color

import cv2
# color image loading: cv2.IMREAD_COLOR
image = cv2.imread("luffy.jpg", cv2.IMREAD_COLOR)
# check image load
if image is None:
    print("Image loading failed, Please check the path!")
else:
    print("Image Shape:", image.shape)
    print("Image:\n", image)
# display image
cv2.imshow("Loaded Image", image)
cv2.waitKey(0)  # press any key, program will end
cv2.destroyAllWindows()

matplotlib

import matplotlib.pyplot as plt
import cv2

# Load Image
image = cv2.imread("luffy.jpg", cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # Convert to RGB format

if image is None:
    print("Image loading failed, Please check the path!")
    exit()

# Display image
plt.imshow(image)
plt.axis("on")  # Display axis
plt.title("Use mouse zoom (Matplotlib)")
plt.show()

convolution

import cv2
import numpy as np
from matplotlib import pyplot as plt

# load image
image = cv2.imread("luffy2.jpg", cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Image loading failed, Please check the path!")
    exit()

# define 3x3 convolution kernel (edge detection kernel)
conv_kernel = np.array([[-1, -1, -1],
                        [-1,  8, -1],
                        [-1, -1, -1]])

# use filter2D function to do convolution for image
edges = cv2.filter2D(image, -1, conv_kernel)

# display original and edge detection image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap="gray")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.title("Convolution 2D Edge Detection Filter")
plt.imshow(edges, cmap="gray")
plt.axis("off")
plt.tight_layout()
plt.show()

canny_edge.py

import cv2
import numpy as np
from matplotlib import pyplot as plt

# Import the image using OpenCV's imread function.
# The flag cv2.IMREAD_GRAYSCALE ensures the image is loaded in grayscale mode.
image = cv2.imread("luffy.jpg", cv2.IMREAD_GRAYSCALE)

# If the image failed to load (e.g., incorrect path or missing file), print an error message and exit the program.
if image is None:
    print("Image loading failed, Please check the path!")
    exit()

# Define the lower and upper thresholds for the Canny edge detector.
# The choice of these threshold values can significantly affect the resulting edge map.
# A lower threshold results in more detected edges (potentially including noise),
# while a higher threshold produces fewer edges (potentially ignoring some details).
low_threshold = 50
high_threshold = 150

# Apply the Canny edge detector using the specified threshold values.
# cv2.Canny() will output an image (edges) containing the detected edges as white on black.
edges = cv2.Canny(image, low_threshold, high_threshold)

# Set up a figure using Matplotlib to display both images side-by-side.
plt.figure(figsize=(10, 5))

# Display the original grayscale image on the left subplot.
plt.subplot(1, 2, 1)
plt.title("Original Image")      # Add a title to the subplot.
plt.imshow(image, cmap="gray")   # Show the image in a grayscale colormap.
plt.axis("off")                  # Hide the axis ticks and labels for a cleaner look.

# Display the edge detection result on the right subplot.
plt.subplot(1, 2, 2)
plt.title(f"Canny Edges (Low: {low_threshold}, High: {high_threshold})")  # Dynamically include threshold values in the title.
plt.imshow(edges, cmap="gray")   # Display the edges in a grayscale colormap.
plt.axis("off")                  # Hide the axis ticks and labels.

# Use tight_layout() to reduce overlaps and automatically adjust subplot parameters for a neat layout.
plt.tight_layout()

# Finally, show the figure with the original image and the edge-detected image side-by-side.
plt.show()

0개의 댓글