Go - Resizing an Image

发布时间 2023-10-10 15:56:54作者: ZhangZhihuiAAA

Problem: You want to resize an image, making it larger or smaller.


Solution: Convert an image to a grid of pixels as the source and create a new image with the resized dimensions. Use the nearest neighbor interpolation algorithm to figure out the color of each pixel in the new image. Convert the grid of pixels back into a resized image.

 

Resizing a raster image means creating an image with a higher or lower number of pixels. Many algorithms are used for resizing images, including nearest neighbor, bilinear, bicubic, Lanczos resampling, and box sampling. Among these algorithms, the nearest neighbor is probably the simplest. However, the quality is usually not the best, and it can also introduce jaggedness in the image.
The nearest neighbor interpolation algorithm works like this:
1 Assume you are given the original image and the scale of the resize. For example, if you want to double the size of the image, the scale is 2.
2 Create a new image with the new size.
3 Take each pixel in the new image, and divide the X and Y positions by the scale to get X ' and Y ' positions. These might not be whole numbers.
4 Find the floor of X ' and Y ' . These are the corresponding X and Y positions mapped on the original image.
5 Use the X ' and Y ' positions to get the pixel in the original image and put it into the new image at the X and Y positions.

Here’s the code to implement the algorithm:

func   resize ( grid   [][] color . Color ,   scale   float64 )   ( resized   [][] color . Color )   { 
      xlen ,   ylen   :=   int ( float64 ( len ( grid )) * scale ),   int ( float64 ( len ( grid [ 0 ])) * scale ) 
      resized   =   make ([][] color . Color ,   xlen ) 
      for   i   :=   0 ;   i   <   len ( resized );   i ++   { 
          resized [ i ]   =   make ([] color . Color ,   ylen ) 
      } 
      for   x   :=   0 ;   x   <   xlen ;   x ++   { 
          for   y   :=   0 ;   y   <   ylen ;   y ++   { 
              xp   :=   int ( math . Floor ( float64 ( x )   /   scale )) 
              yp   :=   int ( math . Floor ( float64 ( y )   /   scale )) 
              resized [ x ][ y ]   =   grid [ xp ][ yp ] 
          } 
      } 
      return 
}