Downsample Image by Factor of 2 with OpenCV cv2 (Python)
Downsample an Image by 2 with OpenCV cv2 (Python)
This guide explains how to downsample an image by a factor of 2 using the cv2 module in OpenCV (Python). Follow these easy steps:
**1. Import the necessary module:**pythonimport cv2
**2. Load your image:**pythonimage = cv2.imread('path_to_image.jpg')
Replace 'path_to_image.jpg' with the actual path to your image file.
**3. Downsample the image:**pythondownsampled_image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR)
Here's a breakdown of the resize function parameters:
image: The input image to downsample.*None: We'll let OpenCV calculate the output size automatically based onfxandfy.*fx=0.5: Downscale factor for the width (horizontal). 0.5 means reducing the width by half.*fy=0.5: Downscale factor for the height (vertical). 0.5 means reducing the height by half.*interpolation=cv2.INTER_LINEAR: Specifies the interpolation method to use.cv2.INTER_LINEARperforms bilinear interpolation for a good balance of speed and quality.
**4. Display or save the downsampled image:**pythoncv2.imshow('Downsampled Image', downsampled_image)cv2.waitKey(0) cv2.destroyAllWindows()
This code will:
- Display the downsampled image in a window titled 'Downsampled Image'.* Wait indefinitely for a key press.* Close the window when a key is pressed.
**To save the downsampled image to a file:**pythoncv2.imwrite('downsampled_image.jpg', downsampled_image)
Replace 'downsampled_image.jpg' with your desired filename.
Remember: Replace 'path_to_image.jpg' with your actual image file path. This code effectively reduces the image dimensions by half, resulting in a downsampled image.
原文地址: https://www.cveoy.top/t/topic/RJw 著作权归作者所有。请勿转载和采集!