代码之家  ›  专栏  ›  技术社区  ›  Mittenchops

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

  •  0
  • Mittenchops  · 技术社区  · 7 年前

    我有一个形象:

    >>> 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. 如果映射到7201280 1数组称为图像空间,那么重塑的空间称为什么?数据空间?线性化空间?
    0 回复  |  直到 7 年前
        1
  •  3
  •   Berriel    7 年前

    你不需要这么做。你可以合并 np.nonzero , np.polyfit np.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] 我们选择了。