将多项式拟合变换回图像空间

Mit*_*ops 0 python opencv numpy

我有一个图像:

>>> image.shape
(720, 1280)
Run Code Online (Sandbox Code Playgroud)

我的图像是 0 和 255 的二进制数组。我已经完成了一些粗略的边缘检测,现在我想通过这些点拟合多项式。

我想在图像空间中的原始图像上看到这些点。

据我所知,执行此操作的标准方法是通过重塑来展开 x,y 图像,适合展开的版本,然后重新重塑回原始图像。

pts = np.array(image).reshape((-1, 2))
xdata = pts[:,0]
ydata = pts[:,1]
z1 = np.polyfit(xdata, ydata, 1) 
z2 = np.polyfit(xdata, ydata, 2)  # or quadratic...
f = np.poly1d(z)
Run Code Online (Sandbox Code Playgroud)

现在我有了这个功能,f我该如何使用它在原始图像空间中绘制线条?

尤其:

  1. .reshape() 返回图像空间的正确反向索引是什么?
  2. 这似乎有点麻烦。这种重塑重塑舞蹈是图像处理中常见的事情吗?上面描述的是执行此操作的标准方法,还是有不同的方法?
  3. 如果映射到 720, 1280, 1 数组上称为图像空间,那么重塑后的空间称为什么?数据空间?线性空间?

Ber*_*iel 5

你不需要这样做。您可以组合np.nonzero,np.polyfitnp.polyval来执行此操作。它看起来像这样:

import numpy as np
from matplotlib import pyplot as plt

# in your case, you would read your image
# > cv2.imread(...)  # import cv2 before
# but we are going to create an image based on a polynomial
img = np.zeros((400, 400), dtype=np.uint8)
h, w = img.shape
xs = np.arange(150, 250)
ys = np.array(list(map(lambda x: 0.01 * x**2 - 4*x + 600, xs))).astype(np.int)
img[h - ys, xs] = 255

# I could use the values I have, but if you have a binary image,
# you will need to get them, and you could do something like this
ys, xs = np.nonzero(img)  # use (255-img) if your image is inverted
ys = h - ys

# compute the coefficients
coefs = np.polyfit(xs, ys, 2)
xx = np.arange(0, w).astype(np.int)
yy = h - np.polyval(coefs, xx)

# filter those ys out of the image, because we are going to use as index
xx = xx[(0 <= yy) & (yy < h)]
yy = yy[(0 <= yy) & (yy < h)].astype(np.int) # convert to int to use as index

# create and display a color image just to viz the result
color_img = np.repeat(img[:, :, np.newaxis], 3, axis=2)
color_img[yy, xx, 0] = 255  # 0 because pyplot is RGB
f, ax = plt.subplots(1, 2)
ax[0].imshow(img, cmap='gray')
ax[0].set_title('Binary')
ax[1].imshow(color_img)
ax[1].set_title('Polynomial')
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果如下:

样本多项式

如果您打印coefs,您将得到[ 1.00486819e-02 -4.01966712e+00 6.01540472e+02]与我们选择的非常接近的结果[0.01, -4, 600]