【问题标题】:Convert floodfill open cv from c++ to python将floodfill open cv从c ++转换为python
【发布时间】:2017-10-09 08:15:48
【问题描述】:

我正在将一个 opencv 代码从 c++ 转换为 python 并卡在 Floodfill 附近的某个地方。

c++ 实现是

Mat floodFilled = cv::Mat::zeros(dilateGrad.rows+2, dilateGrad.cols+2, CV_8U);
floodFill(dilateGrad, floodFilled, cv::Point(0, 0), 0, 0, cv::Scalar(), cv::Scalar(), 4 + (255 << 8) + cv::FLOODFILL_MASK_ONLY);
floodFilled = cv::Scalar::all(255) - floodFilled;
Mat temp;
floodFilled(Rect(1, 1, dilateGrad.cols-2, dilateGrad.rows-2)).copyTo(temp);

我的python实现

h, w = dilateGrad.shape[:2]
floodFilled =np.zeros((h+2,w+2),dtype = np.uint8)
cv2.floodFill(dilateGrad,floodFilled,(0,0),255,cv2.FLOODFILL_MASK_ONLY)
floodFilled =  np.all(255) - floodFilled
floodFilled = cv2.rectangle(dilateGrad,1,1,(h-2,w-2),floodFilled,cv2.CV_8U)

我是 python 中的 opencv 新手,感谢任何人的帮助。

【问题讨论】:

  • 有什么问题?
  • @GPPK 我无法解码 Floodfill 的最后一部分,即为 Floodfill 创建一个标量值以及如何创建矩形

标签: python c++ opencv


【解决方案1】:

C++ 代码最后一行中的Rect 运算符用于指定floodFilled Mat 的ROI,并将该ROI 复制到Mat temp

类似的行为可以在python代码中实现如下:

temp = floodFilled[1:h-2, 1:w-2].copy()

至于Scalar 运算符,您必须使用python 的元组代替Scalar。像Scalar::all(255) 将等于tuple([255] * NumberOfChannels)。对于您当前的情况,NumberOfChannels 为 1,因此它仅相当于 255

代替空的Scalar(),只需传递None 作为参数。

您的最终代码可能如下所示:

h, w = dilateGrad.shape[:2]
floodFilled = np.zeros((h+2,w+2), dtype = np.uint8)
cv2.floodFill(dilateGrad, floodFilled, (0,0), 255, None, None, cv2.FLOODFILL_MASK_ONLY)
floodFilled =  (255) - floodFilled
temp = floodFilled[1:h-2, 1:w-2].copy()

仅供参考:

cv2.rectangle函数的作用是在图像上绘制一个矩形。

np.all 评估作为参数传递给它的二进制条件列表,并且仅当列表中的所有条件评估为 True 时才返回 True。

【讨论】:

  • 感谢您提供的信息,但我如何在 python 中使用 c++ 的标量函数。而且我无法正确获取我的 cv2.floodfill,因为我正在获取全黑图像。
  • 谢谢你的正确解释
猜你喜欢
  • 1970-01-01
  • 2014-04-22
  • 2012-10-22
  • 1970-01-01
  • 2014-05-05
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
相关资源
最近更新 更多