OpenCV
Read and Write Images
Load, display, and save images in various formats.
By EZ4Code Team
ioimage
Code
import cv2
# Read (BGR by default)
img = cv2.imread("input.jpg", cv2.IMREAD_COLOR)
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
unchanged = cv2.imread("input.png", cv2.IMREAD_UNCHANGED)
# Show in a window
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Resize on the fly
h, w = img.shape[:2]
small = cv2.resize(img, (w // 2, h // 2))
# Save
cv2.imwrite("small.jpg", small, [cv2.IMWRITE_JPEG_QUALITY, 85])
cv2.imwrite("out.png", img)
print(img.shape, img.dtype)Explanation
imread() loads an image as a NumPy array, defaulting to BGR color order; flags select grayscale or alpha-preserving modes. imshow opens a window, waitKey blocks until a key is pressed, and imwrite persists the array back to disk. JPEG quality is set via the IMWRITE_JPEG_QUALITY parameter.
More OpenCV Snippets
Resize and Crop
Resize with interpolation and crop regions of interest.
Color Conversion
Convert between BGR, RGB, HSV, and grayscale.
Blur and Filter
Smooth and sharpen images with kernels.
Edge Detection
Detect edges with Canny, Sobel, and Laplacian.
Contours
Find, draw, and measure contours.
Face Detection
Detect faces with a Haar cascade classifier.