Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble getting a SubImage of an Image in Go

Tags:

go

I'm doing some image processing in Go, and I'm trying to get the SubImage of an Image.

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)
}

When I try to compile that, I get .\img.go:8: picture.SubImage undefined (type image.Image has no field or method SubImage).

Any thoughts?

like image 682
Chris Avatar asked Apr 18 '13 01:04

Chris


2 Answers

Here is an alternative approach - use a type assertion to assert that my_image has a SubImage method. This will work for any image type which has the SubImage method (all of them except Uniform at a quick scan). This will return another Image interface of some unspecified type.

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())

}

If you wanted to do this a lot then you would create a new type with the SubImage interface and use that.

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

my_sub_image := my_image.(SubImager).SubImage(image.Rect(0, 0, 10, 10))

The usual caveats with type assertions apply - use the ,ok form if you don't want a panic.

like image 102
Nick Craig-Wood Avatar answered Nov 15 '22 05:11

Nick Craig-Wood


Because image.Image doesn't have a method SubImage. You need to use a type assertion to get the appropriate image.* type.

rgbImg := img.(image.RGBA)
subImg := rgbImg.SubImage(...)
like image 45
cthom06 Avatar answered Nov 15 '22 03:11

cthom06