Search code examples
python-3.xopencvimage-processingimage-resizingindex-error

Image resizing, IndexError: list assignment index out of range


I have the assignment to scale/ resize an image without the use functions from external libraries and need to create the algorithm myself, have searched, but the code that I have found on different forums have not worked, but I have come up with a code that I would believe would work, but I get the index error on a side note I also need to make forward and backward mapping in relation to scaling the image.

My code can be seen below

import cv2 as cv

img = cv.imread('Scale.jpg', 1)
cv.imshow('unscaled', img)
h,w = img.shape[:2]
print(h)
print(w)
def resizePixels(pixels,w1,h1,w2,h2) :

   retval = [w2,h2]
   # EDIT: added +1 to remedy an early rounding problem
   x_ratio = (int)((w1<<16)/w2) +1
   y_ratio = (int)((h1<<16)/h2) +1
   #int x_ratio = (int)((w1<<16)/w2)
   #int y_ratio = (int)((h1<<16)/h2)
   #two = int(x2,y2)
   for i in range (h2):
     i += 1
    for j in range(w2):
        j += 1
        x2 = ((j*x_ratio)>>16)
        y2 = ((i*y_ratio)>>16)
        retval[(i*w2)+j] = pixels[(y2*w1)+x2]

   return retval;

dst = resizePixels(img,h,w,300,300)

#cv.imshow('Resize',dst)
cv.waitKey(0)

EDIT: This is the Traceback I receive

Traceback (most recent call last):
File "C:/Users/Asus/PycharmProjects/Scaling/Scaling.py", line 27, in 
<module>
dst = resizePixels(img,h,w,300,300)

File "C:/Users/Asus/PycharmProjects/Scaling/Scaling.py", line 23, in 
resizePixels

retval[(i*w2)+j] = pixels[(y2*w1)+x2]
IndexError: list assignment index out of range

The picture I use to scale


Solution

  • I make some little changes in your code and it works. Read my comment in the code for more detail.

    import cv2 
    import numpy as np
    
    img = cv2.imread('1.png', 0)
    cv2.imshow('unscaled', img)
    
    h,w = img.shape[:2]
    print(h)
    print(w)
    def resizePixels(pixels,w1,h1,w2,h2):
        retval = []
        # EDIT: added +1 to remedy an early rounding problem
        x_ratio = (int)((w1<<16)/w2) +1
        print(x_ratio)
        y_ratio = (int)((h1<<16)/h2) +1
        print(y_ratio)
        #int x_ratio = (int)((w1<<16)/w2)
        #int y_ratio = (int)((h1<<16)/h2)
        #two = int(x2,y2)
        for i in range(h2):
            # no need to have this: i += 1
            for j in range(w2):
                # no need to have this too: j += 1
                x2 = ((j*x_ratio)>>16)
                y2 = ((i*y_ratio)>>16)
                #add pixel values from original image to an array
                retval.append(pixels[y2,x2])
    
        return retval;
    
    ret = resizePixels(img,w,h,300,300)
    # reshape the array to get the resize image
    dst = np.reshape(ret,(300,300))
    
    cv2.imshow('Resize',dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    enter image description here