【问题标题】:How to mask part of an image based on arrays of points如何根据点数组屏蔽图像的一部分
【发布时间】:2019-03-19 12:52:34
【问题描述】:

我想掩盖由我创建的样条线定义的“V”区域之外的所有内容。我追求的结果是一个 3D 数组,其中“V”之外的区域设置为 0 或 255。

我对使用fill_between 不感兴趣,因为我需要感兴趣的区域以便以后使用 CV2 进行处理。 谢谢!

最终图像应如下所示

这是我所拥有的:

import matplotlib.pyplot as plt
from scipy import misc, interpolate

# Show the image  ---------------- |
f = misc.face()
plt.imshow(f)

# Make the V shape ---------------- |
x1 = [200, 400, 600]
y1 = [0, 300, f.shape[0]]

# Fit spline
tck = interpolate.splrep(x1, y1, k=2)
xx1 = range(min(x1), max(x1))
yy1 = interpolate.splev(xx1, tck)

# Repeat
x2 = [700, 850, 960]
y2 = [f.shape[0], 200, 0]

# Fit spline
tck = interpolate.splrep(x2, y2, k=2)
xx2 = range(min(x2), max(x2))
yy2 = interpolate.splev(xx2, tck)

# Plot splines ---------------- |
plt.plot(xx1, yy1, 'r-', lw=4)
plt.plot(xx2, yy2, 'r-', lw=4)
plt.show()

【问题讨论】:

  • 你能显示预期的图像吗?
  • 红线外侧应为黑色。我会更新
  • 所有图像的形状总是相同的吗?
  • 它始终是样条曲线,是的。线路的某些参数可能会发生变化。

标签: python image-processing cv2


【解决方案1】:

一定有更好的方法。但在这里,使用插值和迭代。

import matplotlib.pyplot as plt
from scipy import misc, interpolate

# Show the image  ---------------- |
im = misc.face().copy()
plt.imshow(f)

# Make the V shape ---------------- |
x1 = [200, 400, 600]
y1 = [0, 300, f.shape[0]]

# Fit spline
tck = interpolate.splrep(x1, y1, k=2)
xx1 = range(min(x1), max(x1))
yy1 = interpolate.splev(xx1, tck)

# Repeat
x2 = [700, 850, 960]
y2 = [f.shape[0], 200, 0]

# Fit spline
tck = interpolate.splrep(x2, y2, k=2)
xx2 = range(min(x2), max(x2))
yy2 = interpolate.splev(xx2, tck)

# Plot splines ---------------- |
plt.plot(xx1, yy1, 'r-', lw=4)
plt.plot(xx2, yy2, 'r-', lw=4)

# Solution - Mask the sides
xx_interp = range(im.shape[0])
yy_interp1 = np.round(np.interp(xx_interp, yy1, xx1)).astype(int)
yy_interp2 = np.round(np.interp(xx_interp, yy2[::-1], xx2[::-1])).astype(int)

for y, x1, x2 in list(zip(xx_interp, yy_interp1, yy_interp2)):
    im[y, :x1, :] = 0
    im[y, x2:, :] = 0

plt.imshow(im);

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 2022-01-06
    • 2011-02-19
    • 2021-09-03
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多