search
HomeBackend DevelopmentGolangGolang image manipulation: Learn how to perform histogram equalization and global thresholding of images

Golang image manipulation: Learn how to perform histogram equalization and global thresholding of images

Aug 18, 2023 pm 02:49 PM
Picture manipulationgolang (go)Histogram equalization

Golang image manipulation: Learn how to perform histogram equalization and global thresholding of images

Golang image operation: learn how to perform histogram equalization and global thresholding of images

Introduction:
Image processing is a field of computer vision and image processing one of the important tasks. In practical applications, we often need to perform some image enhancement operations to improve the quality of the image or highlight certain features in the image. This article will introduce how to use Golang to perform histogram equalization and global thresholding operations on images to achieve image enhancement.

1. Histogram equalization
Histogram equalization is a commonly used image enhancement method. It enhances the contrast of the image by adjusting the grayscale distribution of the image pixels. In this method, we first calculate the cumulative histogram of the image, and then adjust the pixel values ​​of the image based on the cumulative histogram.

The following is a simple Golang code example for implementing histogram equalization of images:

package main

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

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

    // 解码图片
    img, _, err := image.Decode(file)
    if err != nil {
        fmt.Println(err)
        return
    }

    // 计算直方图
    hist := histogram(img)

    // 计算累积直方图
    cumHist := cumulativeHistogram(hist)

    // 根据累积直方图对图像进行像素值调整
    newImg := adjustPixels(img, cumHist)

    // 保存处理后的图像
    outFile, err := os.Create("output.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer outFile.Close()

    // 编码图像
    err = jpeg.Encode(outFile, newImg, &jpeg.Options{Quality: 100})
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("图像处理完成!")
}

// 计算直方图
func histogram(img image.Image) []int {
    bounds := img.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    hist := make([]int, 256)

    for y := 0; y < h; y++ {
        for x := 0; x < w; x++ {
            r, _, _, _ := img.At(x, y).RGBA()
            gray := color.Gray{uint8(r / 256)}
            hist[gray.Y]++
        }
    }

    return hist
}

// 计算累积直方图
func cumulativeHistogram(hist []int) []int {
    cumHist := make([]int, len(hist))
    cumHist[0] = hist[0]

    for i := 1; i < len(hist); i++ {
        cumHist[i] = cumHist[i-1] + hist[i]
    }

    return cumHist
}

// 根据累积直方图调整像素值
func adjustPixels(img image.Image, cumHist []int) image.Image {
    bounds := img.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    newImg := image.NewRGBA(bounds)

    for y := 0; y < h; y++ {
        for x := 0; x < w; x++ {
            r, g, b, a := img.At(x, y).RGBA()

            gray := color.Gray{uint8(r / 256)}
            val := uint8(float64(cumHist[gray.Y]) / float64(w*h) * 255)

            newImg.Set(x, y, color.RGBA{val, val, val, uint8(a / 256)})
        }
    }

    return newImg
}

In the above code, we first pass the image package The ##Decode function decodes the input image file into an object of type image.Image. Then, we call the histogram function to calculate the histogram of the image, and the cumulativeHistogram function to calculate the cumulative histogram of the image. Finally, we adjust the pixel values ​​of the image based on the cumulative histogram and save the processed image to a file using the Encode function of the jpeg package.

2. Global thresholding

Global thresholding is a simple but effective image binarization method. It divides the pixel value of the image into two non-overlapping smooth areas, representing the target respectively. Objects and background. This method is typically applied to images with clear foreground and background differences.

The following is a simple Golang code example for global thresholding of images:

package main

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

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

    // 解码图片
    img, _, err := image.Decode(file)
    if err != nil {
        fmt.Println(err)
        return
    }

    // 根据全局阈值对图像进行二值化处理
    newImg := binarize(img)

    // 保存处理后的图像
    outFile, err := os.Create("output.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer outFile.Close()

    // 编码图像
    err = jpeg.Encode(outFile, newImg, &jpeg.Options{Quality: 100})
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("图像处理完成!")
}

// 根据全局阈值对图像进行二值化处理
func binarize(img image.Image) image.Image {
    bounds := img.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    newImg := image.NewRGBA(bounds)

    threshold := calculateThreshold(img)

    for y := 0; y < h; y++ {
        for x := 0; x < w; x++ {
            r, g, b, a := img.At(x, y).RGBA()

            gray := color.Gray{uint8(r / 256)}
            var val uint8
            if gray.Y > threshold {
                val = 255
            } else {
                val = 0
            }

            newImg.Set(x, y, color.RGBA{val, val, val, uint8(a / 256)})
        }
    }

    return newImg
}

// 根据图像的直方图计算全局阈值
func calculateThreshold(img image.Image) uint8 {
    hist := histogram(img)
    totalPixels := img.Bounds().Max.X * img.Bounds().Max.Y

    // 计算背景像素值的总和
    var bgSum, bgCount, fgSum, fgCount int
    for i := 0; i < len(hist); i++ {
        if i <= 128 {
            bgSum += i * hist[i]
            bgCount += hist[i]
        } else {
            fgSum += i * hist[i]
            fgCount += hist[i]
        }
    }

    // 计算背景和前景的平均灰度值
    bgMean := bgSum / bgCount
    fgMean := fgSum / fgCount

    // 根据背景和前景的平均灰度值计算阈值
    return uint8((bgMean + fgMean) / 2)
}

// 计算直方图
func histogram(img image.Image) []int {
    bounds := img.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    hist := make([]int, 256)

    for y := 0; y < h; y++ {
        for x := 0; x < w; x++ {
            r, _, _, _ := img.At(x, y).RGBA()
            gray := color.Gray{uint8(r / 256)}
            hist[gray.Y]++
        }
    }

    return hist
}

In the above code, we first pass the ## of the

image package The #Decode function decodes the input image file into an object of type image.Image. Then, we call the calculateThreshold function to calculate the global threshold of the image. Finally, we binarize the image based on a global threshold and save the processed image to a file using the Encode function of the jpeg package. Summary:

In this article we introduce how to use Golang to perform histogram equalization and global thresholding operations on images. Histogram equalization can be used to improve the contrast of the image, making the image clearer and more distinct; global thresholding can be used to convert the image into a binary image to highlight the target objects in the image. By flexibly using these two methods, we can achieve image enhancement and feature extraction to meet various application needs. In practical applications, we can combine other image processing algorithms to further improve the effect and quality of image processing.

The above is the detailed content of Golang image manipulation: Learn how to perform histogram equalization and global thresholding of 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
Mastering Go Strings: A Deep Dive into the 'strings' PackageMastering Go Strings: A Deep Dive into the 'strings' PackageMay 12, 2025 am 12:05 AM

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

'encoding/binary' Package in Go: Your Go-To for Binary Operations'encoding/binary' Package in Go: Your Go-To for Binary OperationsMay 12, 2025 am 12:03 AM

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Go Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageGo Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageMay 12, 2025 am 12:02 AM

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

How do you use the 'strings' package to manipulate strings in Go?How do you use the 'strings' package to manipulate strings in Go?May 12, 2025 am 12:01 AM

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

How to use the 'bytes' package to manipulate byte slices in Go (step by step)How to use the 'bytes' package to manipulate byte slices in Go (step by step)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

GO bytes package: What are the alternatives?GO bytes package: What are the alternatives?May 11, 2025 am 12:11 AM

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

Manipulating Byte Slices in Go: The Power of the 'bytes' PackageManipulating Byte Slices in Go: The Power of the 'bytes' PackageMay 11, 2025 am 12:09 AM

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go Strings Package: A Comprehensive Guide to String ManipulationGo Strings Package: A Comprehensive Guide to String ManipulationMay 11, 2025 am 12:08 AM

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version