dongluo3331 2018-03-12 17:46
浏览 600
已采纳

gocv:如何使用opencv从蓝色背景切出图像

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.

enter image description here

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:

enter image description here

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.

  • 写回答

3条回答 默认 最新

  • dongpu4141 2018-04-17 21:27
    关注

    So I spent quite some time on this to figure out what I'm missing and finally found the answer to my question in case anyone is interested. It's now clearer to me now why this question hasn't been answered as the solution to it is rather crazy due to gocv API.

    Here is the code that I had to write to get the result I'm after:

    package main
    
    import (
        "fmt"
        "os"
        "path/filepath"
    
        "gocv.io/x/gocv"
    )
    
    func main() {
        // read image
        pizzaPath := filepath.Join("pizza.png")
        pizza := gocv.IMRead(pizzaPath, gocv.IMReadColor)
        if pizza.Empty() {
            fmt.Printf("Failed to read image: %s
    ", pizzaPath)
            os.Exit(1)
        }
        // Convert BGR to HSV image (dont modify the original)
        hsvPizza := gocv.NewMat()
        gocv.CvtColor(pizza, &hsvPizza, gocv.ColorBGRToHSV)
        pizzaChannels, pizzaRows, pizzaCols := hsvPizza.Channels(), hsvPizza.Rows(), hsvPizza.Cols()
        // define HSV color upper and lower bound ranges
        lower := gocv.NewMatFromScalar(gocv.NewScalar(110.0, 50.0, 50.0, 0.0), gocv.MatTypeCV8UC3)
        upper := gocv.NewMatFromScalar(gocv.NewScalar(130.0, 255.0, 255.0, 0.0), gocv.MatTypeCV8UC3)
        // split HSV lower bounds into H, S, V channels
        lowerChans := gocv.Split(lower)
        lowerMask := gocv.NewMatWithSize(pizzaRows, pizzaCols, gocv.MatTypeCV8UC3)
        lowerMaskChans := gocv.Split(lowerMask)
        // split HSV lower bounds into H, S, V channels
        upperChans := gocv.Split(upper)
        upperMask := gocv.NewMatWithSize(pizzaRows, pizzaCols, gocv.MatTypeCV8UC3)
        upperMaskChans := gocv.Split(upperMask)
        // copy HSV values to upper and lower masks
        for c := 0; c < pizzaChannels; c++ {
            for i := 0; i < pizzaRows; i++ {
                for j := 0; j < pizzaCols; j++ {
                    lowerMaskChans[c].SetUCharAt(i, j, lowerChans[c].GetUCharAt(0, 0))
                    upperMaskChans[c].SetUCharAt(i, j, upperChans[c].GetUCharAt(0, 0))
                }
            }
        }
        gocv.Merge(lowerMaskChans, &lowerMask)
        gocv.Merge(upperMaskChans, &upperMask)
        // global mask
        mask := gocv.NewMat()
        gocv.InRange(hsvPizza, lowerMask, upperMask, &mask)
        // cut out pizza mask
        pizzaMask := gocv.NewMat()
        gocv.Merge([]gocv.Mat{mask, mask, mask}, &pizzaMask)
        // cut out the pizza and convert back to BGR
        gocv.BitwiseAnd(hsvPizza, pizzaMask, &hsvPizza)
        gocv.CvtColor(hsvPizza, &hsvPizza, gocv.ColorHSVToBGR)
        // write image to filesystem
        outPizza := "no_pizza.jpeg"
        if ok := gocv.IMWrite(outPizza, hsvPizza); !ok {
            fmt.Printf("Failed to write image: %s
    ", outPizza)
            os.Exit(1)
        }
        // write pizza mask to filesystem
        outPizzaMask := "no_pizza_mask.jpeg"
        if ok := gocv.IMWrite(outPizzaMask, mask); !ok {
            fmt.Printf("Failed to write image: %s
    ", outPizza)
            os.Exit(1)
        }
    }
    

    This code produces the result I was after:

    pizza cut out

    I'm also going to add another picture that shows the im

    image mask

    Now, let's get to code. gocv API function InRange() does not accept Scalar like OpenCV does so you have to do all that crazy image channel splitting and merging dance since you need to pass in Mats as lower and upper bounds to InRange(); these Mat masks have to have the exact number of channels as the image on which you run InRange().

    This brings up another important point: when allocating the Scalars in gocv for this task, I originally used gocv.MatTypeCV8U type which represents single channel color - not enough for HSV image which has three channels -- this is fixed by using gocv.MatTypeCV8UC3 type.

    If I it were possible pass in gocv.Scalars into gocv.InRange() a lot of the boiler plate code would disappear; so would all the unnecessary gocv.NewMat() allocations for splitting and reassembling the channels which are required to create lower and upper bounds channels.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog