Home  >  Article  >  Backend Development  >  Golang image manipulation: How to perform color balance and color conversion on images

Golang image manipulation: How to perform color balance and color conversion on images

王林
王林Original
2023-08-19 09:21:53751browse

Golang image manipulation: How to perform color balance and color conversion on images

Golang image operation: How to perform color balance and color conversion of pictures

Introduction: In the field of image processing, color balance and color conversion are one of the commonly used operations. This article will introduce how to use Go language to perform color balance and color conversion of pictures, and provide corresponding code examples.

1. Color balance
Color balance refers to adjusting the intensity of each color channel in the image to make the overall color of the image more uniform and natural. Commonly used color balance algorithms include brightness balance, white balance and histogram equalization.

  1. Brightness balance
    Brightness balance is achieved by adjusting the distribution of image brightness. The following is a simple sample code to achieve brightness balance:
package main

import (
    "image"
    "image/color"
    "image/png"
    "os"
)

func brightnessBalance(img image.Image) image.Image {
    width := img.Bounds().Dx()
    height := img.Bounds().Dy()

    balanceImg := image.NewRGBA(img.Bounds())

    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            r, g, b, a := img.At(x, y).RGBA()
            r = r * 2
            g = g * 2
            b = b * 2

            balanceImg.Set(x, y, color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
        }
    }

    return balanceImg
}

func main() {
    file, err := os.Open("input.png")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    img, _, err := image.Decode(file)
    if err != nil {
        panic(err)
    }

    balanceImg := brightnessBalance(img)

    outputFile, err := os.Create("output.png")
    if err != nil {
        panic(err)
    }
    defer outputFile.Close()

    err = png.Encode(outputFile, balanceImg)
    if err != nil {
        panic(err)
    }
}

In the above code, we loop through each pixel of the image and combine the red, green and blue channels of each pixel. The value is multiplied by 2 to achieve an increase in overall brightness. By loading the original image and saving the processed image, we can get a color-balanced image.

  1. White balance
    White balance is to eliminate the color cast caused by uneven lighting in the picture. The following is a simple sample code to achieve white balance:
package main

import (
    "image"
    "image/color"
    "image/png"
    "math"
    "os"
)

func whiteBalance(img image.Image) image.Image {
    width := img.Bounds().Dx()
    height := img.Bounds().Dy()

    whiteBalanceImg := image.NewRGBA(img.Bounds())

    var sumR, sumG, sumB float64
    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            r, g, b, a := img.At(x, y).RGBA()
            sumR += math.Log(float64(r))
            sumG += math.Log(float64(g))
            sumB += math.Log(float64(b))
        }
    }
    avgR := math.Exp(sumR / (float64(width * height)))
    avgG := math.Exp(sumG / (float64(width * height)))
    avgB := math.Exp(sumB / (float64(width * height)))

    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            r, g, b, a := img.At(x, y).RGBA()
            r = uint32(math.Log(float64(r)) * avgR / float64(r))
            g = uint32(math.Log(float64(g)) * avgG / float64(g))
            b = uint32(math.Log(float64(b)) * avgB / float64(b))

            whiteBalanceImg.Set(x, y, color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
        }
    }

    return whiteBalanceImg
}

func main() {
    file, err := os.Open("input.png")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    img, _, err := image.Decode(file)
    if err != nil {
        panic(err)
    }

    whiteBalanceImg := whiteBalance(img)

    outputFile, err := os.Create("output.png")
    if err != nil {
        panic(err)
    }
    defer outputFile.Close()

    err = png.Encode(outputFile, whiteBalanceImg)
    if err != nil {
        panic(err)
    }
}

In the above code, we calculate the average of the logarithmic values ​​of all pixels in the image and divide the logarithmic value of each pixel White balance is achieved by multiplying the average and then performing an exponential operation. Similarly, by loading the original image and saving the processed image, we can get the white balanced image.

2. Color conversion
Color conversion refers to converting colors in one color space into colors in another color space. Commonly used color conversions include RGB to HSV and RGB to YUV.

  1. RGB to HSV conversion
    RGB and HSV are two common color spaces. RGB is used to represent the three color components of red, green, and blue, and HSV is used to represent the hue of the color. , saturation and brightness three attributes.

The following is a simple sample code to convert RGB colors to HSV colors:

package main

import (
    "fmt"
    "image/color"
)

func rgbToHsv(r, g, b uint8) (uint16, uint8, uint8) {
    var h, s, v uint16

    max := uint16(r)
    if uint16(g) > max {
        max = uint16(g)
    }
    if uint16(b) > max {
        max = uint16(b)
    }

    min := uint16(r)
    if uint16(g) < min {
        min = uint16(g)
    }
    if uint16(b) < min {
        min = uint16(b)
    }

    v = max
    delta := max - min

    if max != 0 {
        s = uint8(delta) * 255 / uint8(max)
    } else {
        s = 0
    }

    if delta != 0 {
        if max == uint16(r) {
            h = (uint16(g) - uint16(b)) * 60 / delta
            if uint16(g) < uint16(b) {
                h += 360
            }
        } else if max == uint16(g) {
            h = (2 + (uint16(b)-uint16(r))/delta) * 60
        } else {
            h = (4 + (uint16(r)-uint16(g))/delta) * 60
        }
    } else {
        h = 0
    }

    return h, s, uint8(v)
}

func main() {
    r := uint8(255)
    g := uint8(0)
    b := uint8(0)

    h, s, v := rgbToHsv(r, g, b)

    fmt.Printf("RGB(%d, %d, %d) -> HSV(%d, %d, %d)
", r, g, b, h, s, v)
}

In the above code, we pass a series of Calculate and calculate the value of the corresponding HSV color component. We output a pure red RGB color by setting the value of the RGB component to the maximum value of red, and calculate the corresponding HSV color.

  1. RGB to YUV conversion
    YUV is also a common color space, where Y represents brightness and U and V represent chroma. The following is a simple example code for converting RGB colors to YUV colors:
package main

import (
    "fmt"
    "image/color"
)

func rgbToYuv(r, g, b uint8) (uint8, uint8, uint8) {
    y := uint8(float32(r)*0.299 + float32(g)*0.587 + float32(b)*0.114)
    u := uint8((-float32(r)*0.14713 - float32(g)*0.28886 + float32(b)*0.436 + 128) / 2)
    v := uint8((float32(r)*0.615 + float32(g)*0.51499 - float32(b)*0.10001 + 128) / 2)
    return y, u, v
}

func main() {
    r := uint8(255)
    g := uint8(0)
    b := uint8(0)

    y, u, v := rgbToYuv(r, g, b)

    fmt.Printf("RGB(%d, %d, %d) -> YUV(%d, %d, %d)
", r, g, b, y, u, v)
}

In the above code, we calculate the corresponding values ​​through a series of calculations based on the values ​​of the RGB color components. The value of the YUV color component. Similarly, we output a pure red RGB color by setting the value of the RGB component to the maximum value of red, and calculate the corresponding YUV color.

Conclusion: This article introduces the method of color balance and color conversion of images using Go language, and provides corresponding code examples. I hope readers will have a deeper understanding of Golang image operations through this article and be able to apply it to actual projects.

The above is the detailed content of Golang image manipulation: How to perform color balance and color conversion on 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