Skip to content
OpenCV

Read and Write Images

Load, display, and save images in various formats.

#io#image

Code

opencv
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)