duanlongnao0028 2017-06-11 21:20
浏览 223
已采纳

如何在Go中打开图像以获取黑白像素的二进制数据?

I've been trying for sometime to open an image in binary mode with Go. In Python I'd use the Pillow and image.open() (rb mode). Example.

img = Image.open("PNG.png")
pix = img.getdata()  #where 0 is black and 1 is white pixel

That would open the image with very clean binary of white and black dots like the image below. Example In go I've tried os.Open(file.jpg) to open the file.. I've tried decoding it with image.Decode(), I've loaded the file into bytes.Buffer, I've tried fmt.Sprintf("%b", data), all of the solutions give a byte array. Converting that byte array to binary looks nothing like the image above. I've also tried encoding/binary and its the same story with just getting bytes and the binary generated isn't what i want...

Most recently I've tried this

package main

import (
    "fmt"
    "image"
    "image/jpeg"
    "io"
    "log"
    "os"
)

// Pixel struct example
type Pixel struct {
    R int
    G int
    B int
    A int
}

func main() {
    // You can register another format here
    image.RegisterFormat("jpg", "jpg", jpeg.Decode, jpeg.DecodeConfig)

    file, err := os.Open("/Users/marcsantiago/Desktop/2033bb1b194adace86f99c7bb7d72e81.jpg")

    if err != nil {
        log.Fatalln("Error: File could not be opened")

    }

    defer file.Close()

    pixels, err := getPixels(file)

    if err != nil {
        log.Fatalln("Error: Image could not be decoded")
    }
    black := Pixel{0, 0, 0, 255}

    for i := range pixels {
        if pixels[i] == black {
            fmt.Print("0")
        } else {
            fmt.Print("1")
        }

    }
}

func getPixels(file io.Reader) ([]Pixel, error) {
    img, _, err := image.Decode(file)

    if err != nil {
        return nil, err
    }

    bounds := img.Bounds()
    width, height := bounds.Max.X, bounds.Max.Y

    var pixels []Pixel
    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            pixels = append(pixels, rgbaToPixel(img.At(x, y).RGBA()))
        }
    }
    return pixels, nil
}

// img.At(x, y).RGBA() returns four uint32 values; we want a Pixel
func rgbaToPixel(r uint32, g uint32, b uint32, a uint32) Pixel {
    return Pixel{int(r / 257), int(g / 257), int(b / 257), int(a / 257)}
}

So that I can compare the binary against what I expect I converted the rgba to 1 and 0s where 0 == black... it still doesn't match up not even close. Example enter image description here

Help please. I'm out of ideas. PS. This site http://www.dcode.fr/binary-image, also opens the image and generates the data I'm expecting.

UPDATE: This is the image i'm working with.. Image to decode

  • 写回答

1条回答 默认 最新

  • doujiao7520 2017-06-11 23:24
    关注

    For example,

    package main
    
    import (
        "bytes"
        "fmt"
        "image"
        "os"
    
        _ "image/jpeg"
    )
    
    func main() {
        fName := "ggk3Z.jpg"
        f, err := os.Open(fName)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
        defer f.Close()
        img, _, err := image.Decode(f)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
    
        // http://www.dcode.fr/binary-image
        var txt bytes.Buffer
        bounds := img.Bounds()
        for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
            for x := bounds.Min.X; x < bounds.Max.X; x++ {
                r, g, b, _ := img.At(x, y).RGBA()
                bin := "0"
                if float64((r+g+b))/3 > 0.5 {
                    bin = "1"
                }
                txt.WriteString(bin)
            }
            txt.WriteString("
    ")
        }
        fmt.Fprint(os.Stdout, txt.String())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格