Home  >  Article  >  Backend Development  >  Golang image processing: How to perform convex hull detection and contour fitting of images

Golang image processing: How to perform convex hull detection and contour fitting of images

WBOY
WBOYOriginal
2023-08-26 12:36:311057browse

Golang image processing: How to perform convex hull detection and contour fitting of images

Golang image processing: How to perform convex hull detection and contour fitting of images

Abstract: Image processing is one of the important research directions in the field of computer vision. This article will introduce how to use Golang for convex hull detection and contour fitting of images, and provide relevant code examples.

Introduction: Image processing is one of the important applications in the field of computer vision. In the image processing process, convex hull detection and contour fitting are very common operations and can be used for target recognition, edge detection and other applications. This article will focus on how to use Golang for convex hull detection and contour fitting of images.

Part One: Convex Hull Detection

The convex hull is a minimum convex polygon that contains all points. In image processing, we can use convex hull to identify the shape of the target and perform operations such as target positioning and segmentation. The following is a simple sample code:

package main

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

    "github.com/disintegration/imaging"
    "github.com/llgcode/draw2d/draw2dimg"
    "github.com/nfnt/resize"
)

func ConvexHullDetection(inputPath, outputPath string) {
    // 加载图像
    inputImg, err := imaging.Open(inputPath)
    if err != nil {
        log.Fatal(err)
    }

    // 将图像大小调整为指定尺寸
    resizedImg := resize.Resize(800, 0, inputImg, resize.Lanczos3)

    // 将图像转换为灰度图
    grayImg := imaging.Grayscale(resizedImg)

    // 二值化处理
    binaryImg := imaging.AdjustContrast(grayImg, 20)

    // 构建图像的矩形区域
    rectangle := image.Rect(0, 0, binaryImg.Bounds().Size().X, binaryImg.Bounds().Size().Y)

    // 创建画布
    canvas := image.NewRGBA(rectangle)
    draw.Draw(canvas, canvas.Bounds(), binaryImg, image.Point{}, draw.Src)

    // 构建凸包路径
    path := draw2dimg.NewGraphicsPath()

    // 遍历每个像素点
    bounds := binaryImg.Bounds()
    for x := bounds.Min.X; x < bounds.Max.X; x++ {
        for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
            // 获取像素值
            r, _, _, _ := canvas.At(x, y).RGBA()

            // 如果像素为黑色,则添加到凸包路径中
            if r < 65535/2 {
                path.LineTo(float64(x), float64(y))
            }
        }
    }

    // 进行凸包检测
    path.Close()
    hull := path.ConvexHull()

    // 绘制凸包
    context := draw2dimg.NewGraphicContext(canvas)
    context.SetStrokeColor(color.RGBA{R: 255, G: 0, B: 0, A: 255})
    context.SetLineWidth(2)
    for _, point := range hull {
        context.LineTo(float64(point.X), float64(point.Y))
    }
    context.Stroke()

    // 保存图像
    outputFile, err := os.Create(outputPath)
    if err != nil {
        log.Fatal(err)
    }
    defer outputFile.Close()

    err = jpeg.Encode(outputFile, canvas, &jpeg.Options{Quality: 100})
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    inputPath := "input.jpg"
    outputPath := "output.jpg"
    ConvexHullDetection(inputPath, outputPath)
    fmt.Println("凸包检测完成!")
}

Code analysis:

  1. First, we use the imaging library to load the image and resize the image to the specified size.
  2. Next, we convert the image to grayscale and then binarize it.
  3. Create a canvas and draw the binarized image on the canvas.
  4. Construct a convex hull path and traverse each pixel of the image. If the pixel is black, add it to the convex hull path.
  5. Finally, perform convex hull detection and draw the convex hull, and save the result as an image file.

Part 2: Contour Fitting

Contour fitting is to fit the edge of the target to obtain the geometric shape of the target. Here is a simple example code:

package main

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

    "github.com/disintegration/imaging"
    "github.com/llgcode/draw2d/draw2dimg"
    "github.com/nfnt/resize"
)

func ContourFitting(inputPath, outputPath string) {
    // 加载图像
    inputImg, err := imaging.Open(inputPath)
    if err != nil {
        log.Fatal(err)
    }

    // 将图像大小调整为指定尺寸
    resizedImg := resize.Resize(800, 0, inputImg, resize.Lanczos3)

    // 将图像转换为灰度图
    grayImg := imaging.Grayscale(resizedImg)

    // 二值化处理
    binaryImg := imaging.AdjustContrast(grayImg, 20)

    // 构建图像的矩形区域
    rectangle := image.Rect(0, 0, binaryImg.Bounds().Size().X, binaryImg.Bounds().Size().Y)

    // 创建画布
    canvas := image.NewRGBA(rectangle)
    draw.Draw(canvas, canvas.Bounds(), binaryImg, image.Point{}, draw.Src)

    // 构建轮廓路径
    path := draw2dimg.NewGraphicsPath()

    // 遍历每个像素点
    bounds := binaryImg.Bounds()
    for x := bounds.Min.X; x < bounds.Max.X; x++ {
        for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
            // 获取像素值
            r, _, _, _ := canvas.At(x, y).RGBA()

            // 如果像素为黑色,则添加到轮廓路径中
            if r < 65535/2 {
                path.LineTo(float64(x), float64(y))
            }
        }
    }

    // 进行轮廓拟合
    fitting := path.FitPath(5)

    // 绘制轮廓
    context := draw2dimg.NewGraphicContext(canvas)
    context.SetStrokeColor(color.RGBA{R: 255, G: 0, B: 0, A: 255})
    context.SetLineWidth(2)
    for _, bezier := range fitting {
        context.CubicBezierTo(
            float64(bezier.Control1.X), float64(bezier.Control1.Y),
            float64(bezier.Control2.X), float64(bezier.Control2.Y),
            float64(bezier.To.X), float64(bezier.To.Y))
    }
    context.Stroke()

    // 保存图像
    outputFile, err := os.Create(outputPath)
    if err != nil {
        log.Fatal(err)
    }
    defer outputFile.Close()

    err = jpeg.Encode(outputFile, canvas, &jpeg.Options{Quality: 100})
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    inputPath := "input.jpg"
    outputPath := "output.jpg"
    ContourFitting(inputPath, outputPath)
    fmt.Println("轮廓拟合完成!")
}

Code analysis:

  1. Similar to convex hull detection, we first load the image and resize it to the specified dimensions.
  2. Convert the image to grayscale and perform binary processing.
  3. Create a canvas and draw the binarized image on the canvas.
  4. Construct a contour path and traverse each pixel of the image. If the pixel is black, add it to the contour path.
  5. Perform contour fitting, draw the result on the canvas, and save it as an image file.

Conclusion:
This article introduces how to use Golang for convex hull detection and contour fitting of images, and provides relevant code examples. Image processing is one of the important applications in the field of computer vision. Mastering the basic algorithms of image processing is of great significance to understanding and applying computer vision technology. I hope this article can help readers in their study and research in the field of image processing.

The above is the detailed content of Golang image processing: How to perform convex hull detection and contour fitting 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