| | |
| | | |
| | | import ( |
| | | "basic.com/pubsub/protomsg.git" |
| | | "bytes" |
| | | "fmt" |
| | | "github.com/gogo/protobuf/proto" |
| | | "gocv.io/x/gocv" |
| | | "image" |
| | | "image/jpeg" |
| | | "reflect" |
| | | ) |
| | | // 按尺寸去切图 |
| | | func Subimg(dbyte []byte,x0,y0,x1,y1 int,) protomsg.Image{ |
| | | |
| | | bbb := bytes.NewBuffer(dbyte) // 必须加一个buffer 不然没有read方法就会报错 |
| | | m, _, _ := image.Decode(bbb) // 图片文件解码 |
| | | rgbImg := m.(*image.YCbCr) |
| | | subImg := rgbImg.SubImage(image.Rect(x0, y0, x1, y1)) //图片裁剪x0 y0 x1 y1 |
| | | fmt.Println(reflect.TypeOf(subImg)) |
| | | //f, _ := os.Create("./test.jpg") //创建文件 |
| | | //defer f.Close() //关闭文件 |
| | | emptyBuff := bytes.NewBuffer(nil) //开辟一个新的空buff |
| | | jpeg.Encode(emptyBuff, subImg, nil) //img写入到buff |
| | | bytes := emptyBuff.Bytes() |
| | | i := protomsg.Image{} |
| | | proto.Unmarshal(bytes,&i) |
| | | return i |
| | | //f, _ := os.Create("./test.jpg") //创建文件 |
| | | //defer f.Close() //关闭文件 |
| | | //jpeg.Encode(f, subImg, nil) //写入文件 |
| | | jpeg.E |
| | | } |
| | | // 按尺寸去切图 |
| | | func SubImg(i protomsg.Image, x0, y0, x1, y1 int, ) []byte { |
| | | img, _ := gocv.NewMatFromBytes(int(i.Height), int(i.Width), gocv.MatTypeCV8UC3, i.Data) |
| | | rect := image.Rect(EnlargeSize(x0, y0, x1, y1, i)) |
| | | region := img.Region(rect) |
| | | bytes, _ := gocv.IMEncode(".jpg", region) |
| | | return bytes |
| | | } |
| | | |
| | | // 长宽变为一比一,每边各扩百分之20 |
| | | func EnlargeSize(x0, y0, x1, y1 int, i protomsg.Image) (x0_new, y0_new, x1_new, y1_new int) { |
| | | // 先把长宽变为一比一 |
| | | chazhi := (y1 - y0) - (x1 - x0) |
| | | x0 = x0 - chazhi/2 |
| | | if x0 < 0 { |
| | | x0 = 0 |
| | | } |
| | | x1 = x1 + chazhi/2 |
| | | if x1 > int(i.Width) { |
| | | x1 = int(i.Width) |
| | | } |
| | | |
| | | // 再把每边各扩大百分之20 |
| | | enlarge := float32(0.2) |
| | | x0_new = int((1+enlarge)*float32(x0) - enlarge*float32(x1)) |
| | | if x0_new < 0 { |
| | | x0_new = 0 |
| | | } |
| | | x1_new = int((1+enlarge)*float32(x1) - enlarge*float32(x0)) |
| | | if x1_new > int(i.Width) { |
| | | x1_new = int(i.Width) |
| | | } |
| | | y0_new = int((1+enlarge)*float32(y0) - enlarge*float32(y1)) |
| | | if y0_new < 0 { |
| | | y0_new = 0 |
| | | } |
| | | y1_new = int((1+enlarge)*float32(y1) - enlarge*float32(y0)) |
| | | if y1_new > int(i.Height) { |
| | | y1_new = int(i.Height) |
| | | } |
| | | return |
| | | } |