Numpy Resize/Rescale Image

后端 未结 7 2096
轻奢々
轻奢々 2020-12-02 06:38

I would like to take an image and change the scale of the image, while it is a numpy array.

For example I have this image of a coca-cola bottle: bottle-1

Whi

7条回答
  •  醉话见心
    2020-12-02 06:56

    If anyone came here looking for a simple method to scale/resize an image in Python, without using additional libraries, here's a very simple image resize function:

    #simple image scaling to (nR x nC) size
    def scale(im, nR, nC):
      nR0 = len(im)     # source number of rows 
      nC0 = len(im[0])  # source number of columns 
      return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]  
                 for c in range(nC)] for r in range(nR)]
    

    Example usage: resizing a (30 x 30) image to (100 x 200):

    import matplotlib.pyplot as plt
    
    def sqr(x):
      return x*x
    
    def f(r, c, nR, nC):
      return 1.0 if sqr(c - nC/2) + sqr(r - nR/2) < sqr(nC/4) else 0.0
    
    # a red circle on a canvas of size (nR x nC)
    def circ(nR, nC):
      return [[ [f(r, c, nR, nC), 0, 0] 
                 for c in range(nC)] for r in range(nR)]
    
    plt.imshow(scale(circ(30, 30), 100, 200))
    

    Output:

    This works to shrink/scale images, and works fine with numpy arrays.

提交回复
热议问题