ZhangZhihui's Blog  

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
}
复制代码

 

posted on   ZhangZhihuiAAA  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示