慕田峪9158850
你不需要这样做。你可以结合np.nonzero,np.polyfit和np.polyval来做到这一点。它看起来像这样:import numpy as npfrom 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 polynomialimg = np.zeros((400, 400), dtype=np.uint8)h, w = img.shapexs = 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 thisys, xs = np.nonzero(img) # use (255-img) if your image is invertedys = h - ys# compute the coefficientscoefs = 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 indexxx = 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 resultcolor_img = np.repeat(img[:, :, np.newaxis], 3, axis=2)color_img[yy, xx, 0] = 255 # 0 because pyplot is RGBf, 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()结果如下所示:如果您打印coefs,您将拥有[ 1.00486819e-02 -4.01966712e+00 6.01540472e+02]与[0.01, -4, 600]我们选择的非常接近的。