Skip to content

Commit 76a80c7

Browse files
authored
Merge pull request #94 from evan176/master
Speed up ToImage function
2 parents a00786b + 7ca54e6 commit 76a80c7

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

opencv/goimage.go

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package opencv
22

3+
import "C"
34
import (
45
"image"
56
"image/color"
@@ -59,19 +60,27 @@ func FromImageUnsafe(img *image.RGBA) *IplImage {
5960

6061
/* ToImage converts a opencv.IplImage to an go image.Image */
6162
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))
6365
if img.Depth() != IPL_DEPTH_8U {
6466
return nil // TODO return error
6567
}
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]
6672

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)
7584
}
7685
}
7786

0 commit comments

Comments
 (0)