testing out opencv's resizing functions but i keep getting this error

Question:

been tinkering with python’s open cv library and wanted to try resizing an image.

import cv2 as cv

img = cv.imread("photos/volcano.JPEG")

if img is None:
    sys.exit("Could not read the image.")

def rescaled_img(img, scale=.5):
    width = int(img.shape[2] * scale)
    height = int(img.shape[2] * scale)
    dimensions = (width, height)

    return cv.resize(dimensions, img, interpolation=cv.INTER_AREA)

imgresized = rescaled_img(img)

cv.imshow("volcano", img)
cv.imshow("resized", imgresized)

k = cv.waitKey(0)

if k == ord("s"):
    cv.imwrite("volcano.JPEG", img)

after running this code on the atom text editor’s console i get:

return cv.resize(dimensions, img, interpolation=cv.INTER_AREA)
cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'resize'
> Overload resolution failed:
>  - Can't parse 'dsize'. Expected sequence length 2, got 1271
>  - Can't parse 'dsize'. Expected sequence length 2, got 1271

Any idea what as to what I am doing wrong?
I am still new to coding and using stackoverflow so I apologize if I sound ignorant here.

Asked By: Karthik

||

Answers:

I think you got the parameter order wrong in cv.resize

return cv.resize(dimensions, img, interpolation=cv.INTER_AREA)

This is the function I use:

def resize(src, factor, interpolation=cv.INTER_AREA):
    """ Resizes an image by the specified factor keeping the aspect ratio

    :param src: Image to be resized
    :param scale: Resize factor
    :param interpolation:
    :return: Resized image
    """
    height = src.shape[0]
    width = src.shape[1]
    dimensions = (int(height*factor), int(width*factor))
    return cv.resize(src, dimensions, interpolation)

Also, you can use imutils library (https://github.com/jrosebr1/imutils), that already implements a couple of useful functions for OpenCV.

Answered By: Joan Puigcerver

i got the answer for your problem.
you have to convert your width and height to integer numbers to use them.
see my resize function code:

def rescaleimage(frame,scale,interpolation=cv.INTER_AREA):
   width = int(frame.shape[1] * scale)
   height = int(frame.shape[0] * scale)
   dimensions = (width,height)
   return cv.resize(frame,dimensions,interpolation)
Answered By: amireza
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.