Home  >  Article  >  Backend Development  >  Golang image manipulation: learn how to threshold and denoise images

Golang image manipulation: learn how to threshold and denoise images

王林
王林Original
2023-08-25 10:31:55725browse

Golang image manipulation: learn how to threshold and denoise images

Golang Image Operation: Learn how to threshold and denoise images

Introduction
In the fields of image processing and computer vision, thresholding and denoising is a common image processing operation. This article will introduce how to use Golang to threshold and denoise images, and provide corresponding code examples.

  1. Thresholding
    Thresholding is a common processing method to convert a color or grayscale image into a black and white image. This method compares the brightness value of image pixels with a given threshold and divides the pixel values ​​into two categories: pixels above the threshold are white, and pixels below the threshold are black.

First, we need to install Golang’s image processing package-github.com/disintegration/imaging, install it through the following command:

go get -u github.com/disintegration/imaging

Next , we can write code to implement thresholding of images:

package main

import (
    "image"
    "image/color"
    "image/jpeg"
    "log"
    "os"

    "github.com/disintegration/imaging"
)

func main() {
    // 打开图像文件
    file, err := os.Open("input.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // 解码图像
    img, err := jpeg.Decode(file)
    if err != nil {
        log.Fatal(err)
    }

    // 阈值化处理
    threshold := 128
    bounds := img.Bounds()
    grayImage := image.NewGray(bounds)

    for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
        for x := bounds.Min.X; x < bounds.Max.X; x++ {
            originalColor := img.At(x, y)
            red, green, blue, _ := originalColor.RGBA()
            grayValue := (int(red) + int(green) + int(blue)) / 3

            var colorValue uint8
            if grayValue > threshold {
                colorValue = 255
            } else {
                colorValue = 0
            }

            grayImage.Set(x, y, color.Gray{colorValue})
        }
    }

    // 保存阈值化后的图像
    outputFile, err := os.Create("output.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer outputFile.Close()

    jpeg.Encode(outputFile, grayImage, nil)
}

The above code first opens the image file named input.jpg and uses jpeg.DecodeFunction to decode the image. Then, we create a new grayscale image to save the thresholded result. Next, we iterate through each pixel of the image, calculate its grayscale value, and set the pixel to black or white depending on the threshold. Finally, we use the jpeg.Encode function to save the result as output.jpg.

  1. Denoising
    Image denoising refers to the process of reducing or eliminating noise in the image through certain algorithms and techniques during image processing. Common image denoising algorithms include median filtering, Gaussian filtering, etc.

We can use Golang's draw package to implement a simple median filtering algorithm:

package main

import (
    "image"
    "image/color"
    "image/jpeg"
    "log"
    "os"
)

func medianFilter(img image.Image, size int) image.Image {
    bounds := img.Bounds()
    result := image.NewRGBA(bounds)

    for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
        for x := bounds.Min.X; x < bounds.Max.X; x++ {
            mr, mg, mb := 0, 0, 0
            count := 0

            for dy := -size; dy <= size; dy++ {
                for dx := -size; dx <= size; dx++ {
                    nx := x + dx
                    ny := y + dy

                    if nx >= bounds.Min.X && nx < bounds.Max.X && ny >= bounds.Min.Y && ny < bounds.Max.Y {
                        r, g, b, _ := img.At(nx, ny).RGBA()
                        mr += int(r)
                        mg += int(g)
                        mb += int(b)
                        count++
                    }
                }
            }

            rr := uint8(mr / count)
            gg := uint8(mg / count)
            bb := uint8(mb / count)

            result.Set(x, y, color.RGBA{rr, gg, bb, 255})
        }
    }

    return result
}

func main() {
    // 打开图像文件
    file, err := os.Open("input.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // 解码图像
    img, err := jpeg.Decode(file)
    if err != nil {
        log.Fatal(err)
    }

    // 中值滤波处理
    filtered := medianFilter(img, 1)

    // 保存去噪后的图像
    outputFile, err := os.Create("output.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer outputFile.Close()

    jpeg.Encode(outputFile, filtered, nil)
}

In the above code, we define a medianFilter function to implement a simple median filtering algorithm. In the function, we use a size parameter to specify the size of the filter window. We loop through each pixel of the image and calculate the median value of that pixel based on the pixels within the window and save the result to the newly created image. Finally, we use the jpeg.Encode function to save the result as output.jpg.

Summary
This article introduces how to use Golang to threshold and denoise images. Thresholding can convert color or grayscale images into black and white images for subsequent processing. Denoising can reduce or eliminate noise in images and improve image quality. Through sample code, we can better understand and apply these image processing techniques. I hope this article can be helpful to your study and practice in the field of image processing.

The above is the detailed content of Golang image manipulation: learn how to threshold and denoise images. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn