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

时间:2019-04-09 18:35:41

标签: python numpy opencv

我有一张图片:

>>> image.shape
(720, 1280)

我的图像是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)

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

尤其是:

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

1 个答案:

答案 0 :(得分:2)

您不需要这样做。您可以结合使用np.nonzeronp.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()

结果如下:

Sample Polynomial

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