无法在Go中获取图像的SubImage

Chr*_*ris 6 go

我正在Go中进行一些图像处理,我正在尝试获取图像的SubImage.

import (
  "image/jpeg"
  "os"
)
func main(){
  image_file, err := os.Open("somefile.jpeg")
  my_image, err := jpeg.Decode(image_file)
  my_sub_image := my_image.SubImage(Rect(j, i, j+x_width, i+y_width)).(*image.RGBA)
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我得到了.\img.go:8: picture.SubImage undefined (type image.Image has no field or method SubImage).

有什么想法吗?

Nic*_*ood 10

这是另一种方法 - 使用类型断言断言my_image有一个SubImage方法.这适用于任何具有该方法的图像类型SubImage(除Uniform快速扫描外所有图像类型).这将返回Image某个未指定类型的另一个接口.

package main

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

func main() {
    image_file, err := os.Open("somefile.jpeg")
    if err != nil {
        log.Fatal(err)
    }
    my_image, err := jpeg.Decode(image_file)
    if err != nil {
        log.Fatal(err)
    }

    my_sub_image := my_image.(interface {
        SubImage(r image.Rectangle) image.Image
    }).SubImage(image.Rect(0, 0, 10, 10))

    fmt.Printf("bounds %v\n", my_sub_image.Bounds())

}
Run Code Online (Sandbox Code Playgroud)

如果你想做很多事情,那么你将SubImage使用界面创建一个新类型并使用它.

type SubImager interface {
    SubImage(r image.Rectangle) image.Image
}

my_sub_image := my_image.(SubImager).SubImage(image.Rect(0, 0, 10, 10))
Run Code Online (Sandbox Code Playgroud)

类型断言的常见警告适用 - ,ok如果您不想恐慌,请使用表单.


cth*_*m06 6

因为image.Image没有方法SubImage.您需要使用类型断言来获取适当的image.*类型.

rgbImg := img.(image.RGBA)
subImg := rgbImg.SubImage(...)
Run Code Online (Sandbox Code Playgroud)