cv2.rectangle() 是否有一个名为“rec”的参数?

Does cv2.rectangle() have an argument named “rec”?

我试图在图像中绘制一些矩形,但系统给出了这个错误:

这是我的代码:

cv2.rectangle(img=sample,
                      pt1=(box[0], box[1]),
                      pt2=(box[2], box[3]),
                      color=(220, 0, 0), thickness=2)

如有任何建议,我们将不胜感激!

PS:我在 kaggle notebok 上尝试了这段代码,它 运行 成功了,但是当我想应用 streamlit 部署网络应用程序(使用我的本地机器)时它崩溃了。不确定它是否有所作为,仅供参考。

一定是你的pt1或者pt2有问题,所以cv2.rectangle在构造的时候遇到了找pt1或者pt2的问题一个矩形。

我可以通过以下代码重现您的错误:

fig, ax = plt.subplots(1, 1, figsize=(10, 10))
img = np.ones((128, 128))
x1, y1, x2, y2 = 20, 30, 70, 90
line_width = 2
color = (0, 255, 255)

img = cv2.rectangle(img=img,
                    pt2=(x1, y1),
                    color=color,
                    thickness=line_width)

ax.imshow(img)

但是,如果你给cv2.rectangle 正确的 pt1 和 pt2,你可以得到正确的答案。

fig, ax = plt.subplots(1, 1, figsize=(10, 10))
img = np.ones((128, 128))
x1, y1, x2, y2 = 20, 30, 70, 90
line_width = 2
color = (0, 255, 255)
img = cv2.rectangle(img=img,
                    pt1=(x1, y1),
                    pt2=(x2, y2),
                    color=color,
                    thickness=line_width)

ax.imshow(img)

你可以试试上面这段代码调试一下

这个问题我搞定了,是版本的问题。当我降级到4.1.0.25时,问题就解决了。

cv2.rectangle 有错误;如果您向它传递无效值的参数,它会尝试调用错误的重载。

这是因为在c++中,矩形有两个重载,见documentation:

void cv::rectangle (InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)

void cv::rectangle (InputOutputArray img, Rect rec, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)

但是,python 包装器不会将其表示为两个函数,python 包装器将尝试根据参数的 类型调用正确的函数 提供给它,而不是参数的名称。

如果你阅读https://docs.opencv.org/master/da/d49/tutorial_py_bindings_basics.html,你会看到:

Overloaded functions can be extended using CV_EXPORTS_AS. But we need to pass a new name so that each function will be called by that name in Python. Take the case of integral function below. Three functions are available, so each one is named with a suffix in Python. Similarly CV_WRAP_AS can be used to wrap overloaded methods.

但是,如果您检查源代码,则不会这样做。

这已在之前的 opencv 中作为错误归档 here and here, specifically see the comment from the opencv developers here: https://github.com/opencv/opencv/issues/15465#issuecomment-758025129

The root cause of the issue is current implementation of the overload resolution in the generated Python bindings. In my opinion, to solve the problem with inappropriate/misleading message the following steps should be done: ... If the last overload fits - use it and forget about previous errors. Otherwise raise custom OpenCV exception of OverloadError type with previously collected messages.

这已在 https://github.com/opencv/opencv/pull/19312 中解决,并合并到 opencv 的某些未来版本中。

即。长话短说:这是一个错误。它现在已修复,但可能不在您之前使用的 opencv 版本上。

原因很可能是 pt1 和 pt2 类型不是 'int',这导致 opencv 尝试调用错误的重载,但它引发了不正确的错误消息。