【问题标题】:Why cv2.line can't draw on 1 channel numpy array slice inplace?为什么 cv2.line 不能就地绘制 1 通道 numpy 数组切片?
【发布时间】:2019-12-23 17:00:53
【问题描述】:

为什么 cv2.line 不能就地绘制 1 通道 numpy 数组切片?

print('cv2.__version__', cv2.__version__)

# V1
print('-'*60)
a = np.zeros((20,20,4), np.uint8)
cv2.line(a[:,:,1], (4,4), (10,10), color=255, thickness=1)
print('a[:,:,1].shape', a[:,:,1].shape)
print('np.min(a), np.max(a)', np.min(a), np.max(a))

# V2
print('-' * 60)
b = np.zeros((20,20), np.uint8)
cv2.line(b, (4,4), (10,10), color=255, thickness=1)
print('b.shape', b.shape)
print('np.min(b), np.max(b)', np.min(b), np.max(b))

输出:

cv2.__version__ 4.1.0
------------------------------------------------------------
a[:,:,1].shape (20, 20)
np.min(a), np.max(a) 0 0
------------------------------------------------------------
b.shape (20, 20)
np.min(b), np.max(b) 0 255

似乎错误信息取决于 opencv 版本:

cv2.__version__ 3.4.3
------------------------------------------------------------
Traceback (most recent call last):
  File "test_me.py", line 11, in <module>
    cv2.line(a[:,:,1], (4,4), (10,10), color=255, thickness=1)
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)

【问题讨论】:

  • color=255 在语义上是什么意思?
  • @WillemVanOnsem 在单通道图像上用 255 画线。

标签: python numpy opencv


【解决方案1】:

有趣的问题。鉴于错误:

输出数组 img 的布局与 cv::Mat 不兼容(step[ndims-1] != elemsize 或 step[1] != elemsize*nchannels)

我认为这可能是由于 numpy 中的视图/副本之间的差异造成的。 read1read2

为了比较,以下方法不起作用:

x = a[:,:,1]
cv2.line(x, (4,4), (10,10), color=255, thickness=1)
a[:,:,1] = x

虽然以下是:

x = np.copy(a[:,:,1])
cv2.line(x, (4,4), (10,10), color=255, thickness=1)
a[:,:,1] = x

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 2020-09-16
    • 2010-12-13
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多