I started playing with gocv. I'm trying to figure out a simple thing: how to cut out an object from an image which has a background of certain colour. In this case the object is pizza and background colour is blue.
I'm using InRange function (inRange in OpenCV) to define the upper and lower threshold for blue colour to create a mask and then CopyToWithMask function (copyTo in OpenCV) to apply the mask on the original image. I expect the result to be the blue background with the pizza cut out of it.
The code is very simple:
package main
import (
"fmt"
"os"
"gocv.io/x/gocv"
)
func main() {
imgPath := "pizza.png"
// read in an image from filesystem
img := gocv.IMRead(imgPath, gocv.IMReadColor)
if img.Empty() {
fmt.Printf("Could not read image %s
", imgPath)
os.Exit(1)
}
// Create a copy of an image
hsvImg := img.Clone()
// Convert BGR to HSV image
gocv.CvtColor(img, hsvImg, gocv.ColorBGRToHSV)
lowerBound := gocv.NewMatFromScalar(gocv.NewScalar(110.0, 100.0, 100.0, 0.0), gocv.MatTypeCV8U)
upperBound := gocv.NewMatFromScalar(gocv.NewScalar(130.0, 255.0, 255.0, 0.0), gocv.MatTypeCV8U)
// Blue mask
mask := gocv.NewMat()
gocv.InRange(hsvImg, lowerBound, upperBound, mask)
// maskedImg: output array that has the same size and type as the input arrays.
maskedImg := gocv.NewMatWithSize(hsvImg.Rows(), hsvImg.Cols(), gocv.MatTypeCV8U)
hsvImg.CopyToWithMask(maskedImg, mask)
// save the masked image
newImg := gocv.NewMat()
// Convert back to BGR before saving
gocv.CvtColor(maskedImg, newImg, gocv.ColorHSVToBGR)
gocv.IMWrite("no_pizza.jpeg", newImg)
}
However the resulting image is basically almost completely black except for a slight hint of a pizza edge:
As for the chosen upper and lower bound of blue colours, I followed the guide mentioned in the official documentation:
blue = np.uint8([[[255, 0, 0]]])
hsv_blue = cv2.cvtColor(blue, cv2.COLOR_BGR2HSV)
print(hsv_blue)
[[[120 255 255]]]
Now you take [H-10, 100,100] and [H+10, 255, 255] as lower bound and upper bound respectively.
I'm sure I'm missing something fundamental, but can't figure out what it is.