I would like to resize images using OpenCV python library. It works but the quality of the image is pretty bad.
I must say, I would like to use these images for a photo sharing website, so the quality is a must.
Here is the code I have for the moment:
[...]
_image = image
height, width, channels = _image.shape
target_height = 1000
scale = height/target_height
_image = cv2.resize(image, (int(width/scale), int(height/scale)), interpolation = cv2.INTER_AREA)
cv2.imwrite(local_output_temp_file,image, (cv2.IMWRITE_JPEG_QUALITY, 100))
[...]
I don't know if there are others parameters to be used to specify the quality of the image.
Thanks.
The first step is to create an object of the DNN superresolution class. This is followed by the reading and setting of the model, and finally, the image is upscaled. We have provided the Python and C++ codes below. You can replace the value of the model_path variable with the path of the model that you want to use.
To resize an image in Python, you can use cv2. resize() function of OpenCV library cv2. Resizing, by default, does only change the width and height of the image. The aspect ratio can be preserved or not, based on the requirement.
You can try using imutils.resize
to resize an image while maintaining aspect ratio. You can adjust based on desired width
or height
to upscale or downscale. Also when saving the image, you should use a lossless image format such as .tiff
or .png
. Here's a quick example:
Input image with shape 250x250
Downscaled image to 100x100
Reverted image back to 250x250
import cv2
import imutils
image = cv2.imread('1.png')
resized = imutils.resize(image, width=100)
revert = imutils.resize(resized, width=250)
cv2.imwrite('resized.png', resized)
cv2.imwrite('original.png', image)
cv2.imwrite('revert.png', revert)
cv2.waitKey()
Try to use more accurate interpolation techniques like cv2.INTER_CUBIC
or cv2.INTER_LANCZOS64
. Try also switching to scikit-image
. Docs are better and lib is more reach in features. It has 6 modes of interpolation to choose from:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With