Home Backend Development Golang Golang 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 manipulation golang (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
}
Copy after login

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
}
Copy after login
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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
Golang image manipulation: how to mirror, rotate and flip images Golang image manipulation: how to mirror, rotate and flip images Aug 25, 2023 pm 10:31 PM

Golang image manipulation: How to mirror, rotate and flip images 1. Introduction Image processing is one of the needs we often encounter in many development scenarios. In Golang, we can use the image package to operate and process images. This article will focus on how to use Golang to mirror, rotate and flip images, and provide corresponding code examples. 2. Mirroring operation Mirroring a picture is to change the left and right layout of the picture. In Golang, you can use Fli of the draw package

Why is Golang suitable for AI development? Why is Golang suitable for AI development? Sep 08, 2023 pm 01:54 PM

Why is Golang suitable for AI development? With the rapid development of artificial intelligence (AI) technology, more and more developers and researchers have begun to pay attention to the potential of using the Golang programming language in the field of AI. Golang (also known as Go) is an open source programming language developed by Google. It is loved by developers for its high performance, high concurrency and simplicity and ease of use. This article will explore why Golang is suitable for AI development and provide some sample code to demonstrate Golang's advantages in the AI ​​field. High sex

PHP image operation: how to get the size and file size of images PHP image operation: how to get the size and file size of images Aug 26, 2023 am 08:55 AM

PHP Image Operation: How to Get the Size and File Size of Images In developing websites or applications, we often need to process images. Obtaining the size and file size of images is a common requirement, which can be easily achieved through some functions in PHP. This article will introduce how to use PHP to obtain the size and file size of images, and attach a code example. Get the image size To get the image size, you can use PHP's built-in function getimagesize(). This function will return a file containing the image size

Golang development: building a distributed file storage system Golang development: building a distributed file storage system Sep 22, 2023 am 08:00 AM

Golang Development: Building a Distributed File Storage System In recent years, with the rapid development of cloud computing and big data, the demand for data storage has continued to increase. In order to cope with this trend, distributed file storage systems have become an important technical direction. This article will introduce how to build a distributed file storage system using the Golang programming language and provide specific code examples. 1. Design of distributed file storage system A distributed file storage system is a system that stores file data dispersedly on multiple machines. It divides the data into multiple blocks.

Details, techniques and best practices for implementing distributed log collection and analysis with Golang and RabbitMQ Details, techniques and best practices for implementing distributed log collection and analysis with Golang and RabbitMQ Sep 27, 2023 pm 12:31 PM

Details, techniques, and best practices for implementing distributed log collection and analysis with Golang and RabbitMQ. In recent years, with the popularity of microservice architecture and the complexity of large-scale systems, log collection and analysis have become more and more important. In a distributed system, the logs of each microservice are often scattered in different places. How to efficiently collect and analyze these logs becomes a challenge. This article will introduce the details, techniques, and best practices on how to use Golang and RabbitMQ to implement distributed log collection and analysis. Ra

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 Aug 19, 2023 am 09:21 AM

Golang image operation: How to perform color balance and color conversion on images 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. Brightness balanceBrightness balance is achieved by adjusting the graph

Analysis of application scenarios of Goroutines in Golang concurrent programming practice Analysis of application scenarios of Goroutines in Golang concurrent programming practice Jul 18, 2023 pm 05:21 PM

Introduction to the application scenario analysis of Goroutines in Golang concurrent programming practice: With the continuous improvement of computer performance, multi-core processors have become mainstream. In order to make full use of the advantages of multi-core processors, we need to use concurrent programming technology to implement multi-threaded operations. In the Go language, Goroutines (coroutines) are a very powerful concurrent programming mechanism that can be used to achieve efficient concurrent operations. In this article, we will explore the application scenarios of Goroutines and give some examples.

Golang image manipulation: how to perform gradient and texture mapping of images Golang image manipulation: how to perform gradient and texture mapping of images Aug 22, 2023 pm 12:33 PM

Golang image manipulation: How to perform gradient and texture mapping on images Overview: In image processing, gradient and texture mapping are two commonly used techniques. Gradients can create smooth transitions of color effects, while texture mapping can map a texture image to a target image. This article will introduce how to use the Golang programming language to perform gradient and texture mapping operations on images. Image gradient First, we need to import Golang's image processing packages image and image/color. The following is a sample code, created by

See all articles