Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Image using Opencv Python and preserving the quality

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.

like image 574
CC. Avatar asked Dec 09 '19 09:12

CC.


People also ask

How do I change the resolution of an image in OpenCV Python?

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.

How do I resize an image while maintaining its aspect ratio OpenCV?

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.


2 Answers

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

enter image description here

Reverted image back to 250x250

enter image description here

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()
like image 82
nathancy Avatar answered Nov 15 '22 05:11

nathancy


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:

  • 0: Nearest-neighbor
  • 1: Bi-linear (default)
  • 2: Bi-quadratic
  • 3: Bi-cubic
  • 4: Bi-quartic
  • 5: Bi-quintic
like image 43
Piotr Rarus Avatar answered Nov 15 '22 05:11

Piotr Rarus