Engee documentation
Notebook

Image magnification using bilinear interpolation

This example demonstrates image magnification using the bilinear interpolation method.

Introduction

Bilinear interpolation is a method of increasing or decreasing the size of an image while maintaining intermediate pixel values. It is used to ensure that the image does not lose quality and does not look "pixelated" when zooming. The algorithm works by calculating new pixel values based on the weighted average of the nearest pixels. In this example, we implement an image magnification function with a given zoom level using Julia libraries for working with images and interpolation.

In [ ]:
# Установка необходимых пакетов
import Pkg; Pkg.add(["Images", "FileIO", "Interpolations"])
In [ ]:
# Подключение необходимых библиотек
using Images      # Для работы с изображениями
using FileIO      # Для загрузки и сохранения изображений
using Interpolations # Для интерполяции данных, в данном случае — билинейной

The main part

Image magnification function

Declaring an image zoom function

The function takes a pixel matrix (image) and a zoom level

In [ ]:
function enlarge(A::Matrix, factor::AbstractFloat)
    # Получаем исходные размеры изображения
    lx, ly = size(A)

    # Вычисляем новые размеры изображения, умножая старые на коэффициент и округляя до целых чисел
    nx, ny = round.(Int, factor .* (lx, ly))

    # Создаем линейные диапазоны для координат по x и y для нового изображения
    # LinRange создает равномерно распределенные точки между 1 и размером изображения по соответствующей оси
    vx, vy = LinRange(1, lx, nx), LinRange(1, ly, ny)

    # Создаем интерполятор для исходного изображения с использованием билинейной интерполяции
    # BSpline(Linear()) задаёт линейный сплайн, что соответствует билинейной интерполяции в 2D
    itp = interpolate(A, BSpline(Linear()))

    # Применяем интерполятор к новым координатам и возвращаем увеличенное изображение
    return itp(vx, vy)
end
Out[0]:
enlarge (generic function with 1 method)

Image loading and processing

We download the image from the file and convert it into a matrix of pixels of the type RGB{Float64}

This is necessary to work with color images and support interpolation.

In [ ]:
img_s = load(joinpath(@__DIR__,"legio.jpg")) |> Matrix{RGB{Float64}};

Calling the image magnification function with a factor of 1.6

In [ ]:
Alarge = enlarge(img_s, 1.6);

Saving the enlarged image to a file

In [ ]:
save(joinpath(@__DIR__,"LEGIO.jpg"), Alarge);
img_b = load(joinpath(@__DIR__,"LEGIO.jpg")) |> Matrix{RGB{Float64}};
In [ ]:
println("Начальный размер: $(size(img_s)), конечный размер: $(size(img_b))")
Начальный размер: (85, 85), конечный размер: (136, 136)

Conclusion

In this example, we looked at the implementation of the bilinear interpolation algorithm for image magnification in the Julia programming language. We used external libraries to load/save images and perform interpolation. As a result, the script loads the image, enlarges it 1.6 times using bilinear interpolation, and saves the result to a new file. This is useful for working with graphics when you need to increase the image resolution without losing quality.

The example was developed using materials from Rosetta Code