解決GoCV/OpenCV不支持中文的問題

一、imread 不支持中文路徑名,如果圖片文件路徑名中有中文,就會報錯

 imread_('W:\GZGTOOL\Images\壁紙\迪士尼樂園\s04.jpg'): can't open/read file: check file path/integrity

解決辦法

很簡單,參考python中的思路,自己把圖片文件讀出來,然後再用imdecode

 func LoadImage(fp string)(cv.Mat,error){  
   img:=cv.NewMat()
   buf,err:=ioutil.ReadFile(fp)
   if err!=nil{
     return img, err
   }
   err =cv.IMDecodeIntoMat(buf,cv.IMReadAnyColor,&img) 
   return img,err
 }

二、puttext不支持中文,用opcv內置方法puttext寫字符串到圖片上,如果包含中文,只能得到一串”???“

 cv.PutText(&img,fmt.Sprintf("image%d圖片%d",i,i),image.Pt(200,200),cv.FontHersheyComplex,2,color.RGBA{255,0,0,0xff},2)

結果如下:

 

解決辦法

1,據說opencv5.0中已經支持中文了,期待5.0發佈和gocv同步升級

2,使用freetype,參考了大佬這篇文章

 func  WriteTextOnMat(mat *cv.Mat, text string,textPos image.Point, textSize float64, textColor color.RGBA,fontFile string)error{
   img,err:=mat.ToImage()
   if err!=nil{
     return err
   }
   img,err=WriteTextOnImage(img,text,textPos,textSize,textColor,fontFile)
   if err!=nil{
     return err
   }   
   mat2,err:=CvtImageToMat(img)
   if err!=nil{
     return err
   } 
   mat2.CopyTo(mat)
   mat2.Close()
   return nil
 }
 //Image2RGBA Image2RGBA
 func Image2RGBA(img image.Image) *image.RGBA {
   if rgba,ok:=img.(*image.RGBA);ok{
     return rgba
   }
   baseSrcBounds := img.Bounds().Max
   w,h := baseSrcBounds.X, baseSrcBounds.Y
   dst := image.NewRGBA(image.Rect(0, 0, w, h)) 
   //copy圖片
   draw.Draw(dst, dst.Bounds(), img, img.Bounds().Min, draw.Over)
 return dst
 }
 func  WriteTextOnImage(img image.Image, text string,textPos image.Point, textSize float64, textColor color.RGBA,fontFile string)(image.Image,error){
   // Read the font data.
   dpi:=72.0
   fontBytes, err := ioutil.ReadFile
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章