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

问题描述 投票:0回答:1

我有一张图片:

>>> 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阵列称为图像空间,那么称为重塑空间的是什么?数据空间?线性化空间?
python numpy opencv
1个回答
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]

© www.soinside.com 2019 - 2024. All rights reserved.