简体   繁体   中英

How to use numpy.polyfit to fit an graph?

I have an image below. Its shape is 720x1280. I want to draw a line to fit this white pattern.

在此处输入图片说明

I used y range instead of x is because y is more easy to fit as 2nd order polynomial.

y_range = np.linspace(0, 719, num=720) # to cover same y-range as image
fit = np.polyfit(y_range, image, 2) # image.shape = (720, 1280)
print(fit.shape) # (3, 1280)

I expect fit.shape = (3,) , but it's not.

  1. Can np.polyfit() be used in this situation?
  2. If 1. is true, how to do this? I want to use fit to calculate curve as following.

f = fit[0]*y_range**2 + fit[1]*y_range + fit[2]

Thank you.

Your image is 2-D, that is the problem. The 2-D image contains information about the coordinates of each point, so you only have to put it into a suitable format.

Since it seems that you are interested only in the location of the white pixels (and not the particular value of each pixel), convert the image into binary values. I don't know particular values of your image but you could do for example:

import numpy as np
curoff_value = 0.1 # this is particular to your image
image[image > cutoff_value] = 1 # for white pixel
image[image <= cutoff_value] = 0 # for black pixel

Get the coordinates of the white pixels:

coordinates = np.where(image == 1)
y_range = coordinates[0]
x_range = coordinates[1]
fit = np.polyfit(y_range, x_range, 2)
print(fit.shape)

Returns (3, ) as you would expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM