|
1 | 1 | package opencv
|
2 | 2 |
|
| 3 | +import "C" |
3 | 4 | import (
|
4 | 5 | "image"
|
5 | 6 | "image/color"
|
@@ -59,19 +60,27 @@ func FromImageUnsafe(img *image.RGBA) *IplImage {
|
59 | 60 |
|
60 | 61 | /* ToImage converts a opencv.IplImage to an go image.Image */
|
61 | 62 | func (img *IplImage) ToImage() image.Image {
|
62 |
| - out := image.NewNRGBA(image.Rect(0, 0, img.Width(), img.Height())) |
| 63 | + var height, width, channels, step int = img.Height(), img.Width(), img.Channels(), img.WidthStep() |
| 64 | + out := image.NewNRGBA(image.Rect(0, 0, width, height)) |
63 | 65 | if img.Depth() != IPL_DEPTH_8U {
|
64 | 66 | return nil // TODO return error
|
65 | 67 | }
|
| 68 | + // Turn opencv.Iplimage.imageData(*char) to slice |
| 69 | + var limg *C.char = img.imageData |
| 70 | + var limg_ptr unsafe.Pointer = unsafe.Pointer(limg) |
| 71 | + var data []C.char = (*[1 << 30]C.char)(limg_ptr)[:height*step : height*step] |
66 | 72 |
|
67 |
| - for y := 0; y < img.Height(); y++ { |
68 |
| - for x := 0; x < img.Width(); x++ { |
69 |
| - s := img.Get2D(x, y).Val() |
70 |
| - |
71 |
| - b, g, r := s[0], s[1], s[2] |
72 |
| - |
73 |
| - c := color.NRGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: uint8(255)} |
74 |
| - out.Set(x, y, c) |
| 73 | + c := color.NRGBA{R: uint8(0), G: uint8(0), B: uint8(0), A: uint8(255)} |
| 74 | + // Iteratively assign imageData's color to Go's image |
| 75 | + for y := 0; y < height; y++ { |
| 76 | + for x := 0; x < step; x = x + 3 { |
| 77 | + c.B = uint8(data[y*step+x]) |
| 78 | + c.G = uint8(data[y*step+x+1]) |
| 79 | + c.R = uint8(data[y*step+x+2]) |
| 80 | + if channels == 4 { |
| 81 | + c.A = uint8(data[y*step+x+3]) |
| 82 | + } |
| 83 | + out.SetNRGBA(int(x/3), y, c) |
75 | 84 | }
|
76 | 85 | }
|
77 | 86 |
|
|
0 commit comments