5

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.

nathancy
  • 42,661
  • 14
  • 115
  • 137
CC.
  • 2,736
  • 11
  • 53
  • 70

2 Answers2

3

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()
nathancy
  • 42,661
  • 14
  • 115
  • 137
2

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
Piotr Rarus
  • 884
  • 8
  • 16