Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用X和Y值绘制图片_Python_Numpy_Module_Scipy - Fatal编程技术网

Python:使用X和Y值绘制图片

Python:使用X和Y值绘制图片,python,numpy,module,scipy,Python,Numpy,Module,Scipy,我有一系列的方法可以获取89x22像素的图像(虽然理论上大小是无关的),并将曲线拟合到每行像素上,以找到最重要信号的位置。最后,我有一个Y值列表,每行像素一个,还有一个X值列表,每行最高有效峰值的位置 我想测试不同类型的曲线,看看哪些模型的数据更好,为了做到这一点,我想能够打印出一个新的图像,也是89x22像素,其中最重要的峰值的位置标记为每行一个红色像素。我已经附上了一个输入示例和一个(画得不好的)示例,说明我期望良好的输出是什么样子的: 关于开始查找哪些模块有什么建议吗 class ima

我有一系列的方法可以获取89x22像素的图像(虽然理论上大小是无关的),并将曲线拟合到每行像素上,以找到最重要信号的位置。最后,我有一个Y值列表,每行像素一个,还有一个X值列表,每行最高有效峰值的位置

我想测试不同类型的曲线,看看哪些模型的数据更好,为了做到这一点,我想能够打印出一个新的图像,也是89x22像素,其中最重要的峰值的位置标记为每行一个红色像素。我已经附上了一个输入示例和一个(画得不好的)示例,说明我期望良好的输出是什么样子的:

关于开始查找哪些模块有什么建议吗

class image :

    def importImage (self) :
        """Open an image and sort all pixel values into a list of lists"""
        from PIL import Image               #imports Image from PIL library

        im = Image.open("testTop.tif")      #open the file
        size = im.size                      #size object is a tuple with the pixel width and pixel height
        width = size[0]                     #defines width object as the image width in pixels
        height = size[1]                    #defines the height object as the image height in pixels

        allPixels = list(im.getdata())      #makes a list of all pixels values
        pixelList = [allPixels[width*i : width * (i+1)] for i in range(height)]     #takes mega-list and makes a list of lists by row
        return(pixelList)                   #returns list of lists

    def fitCurves (self) :
        """
        Iterate through a list of lists and fit a curve to each list of integers. 
        Append the position of the list and the location of the vertex to a growing list.
        """
        from scipy.optimize import curve_fit
        import numpy as np
        from matplotlib import pyplot as pp
        from scipy.misc import factorial

        image = self.importImage()
        xList = []
        yList = []
        position = 0

        for row in image :
            #Gaussian fit equations kindly provided by user mcwitt
            x = np.arange(len(row))
            ffunc = lambda x, a, x0, s: a*np.exp(-0.5*(x-x0)**2/s**2)   # define function to fit
            p, _ = curve_fit(ffunc, x, row, p0=[100,5,2])           # fit with initial guess a=100, x0=5, s=2
            x0 = p[1]
            yList.append(position)
            position = position + 1
            xList.append(x0)
        print(yList)
        print(xList)

newImage = image()
newImage.fitCurves()
马比:


这太酷了!有没有办法添加一点内联注释?我很想了解更多关于这方面的信息,但并不是所有的代码都是直观的。如果没有,谢谢你!请记住,颜色可能会产生误导。渐变可能不像颜色想象的那样锐利。Cubehelix作为imshow的参数可能是一个更好的选择。你能解释一下为什么最小二乘法最小化的初始估计是一个由三个数字组成的列表吗?我知道提供最大值(作为曲线中心的初始估计值)是多么有利,但我不明白总是通过1和10是多么有利。如果maxIndex估计曲线的中心,那么1和10是否估计曲线的高度和宽度?是的,我还在努力理解这个代码:)参数是振幅、中心和峰值宽度。amp和wid参数取决于您的数据,或者您事先知道良好的估计值,或者您可以尝试互相关。
import numpy as np
from matplotlib import pyplot as plt
from scipy import ndimage
from scipy import optimize
%matplotlib inline

# just a gaussian (copy paste from lmfit, another great package)
def my_gaussian(p,x):
    amp = p[0]
    cen = p[1]
    wid = p[2]
    return amp * np.exp(-(x-cen)**2 /wid)

# I do like to write a cost function separately. For the leastsquare algorithm it should return a vector.
def my_cost(p,data):
    return data - my_gaussian(p,data)

# i load the image and generate the x values
image = ndimage.imread('2d_gaussian.png',flatten=True)
x = np.arange(image.shape[1])
popt = []

# enumerate is a convenient way to loop over an iterable and keep track of the index.
y = []
for index,data in enumerate(image):
    ''' this is the trick to make the algorithm robust. 
    I do plug the index of the maximum value of the current row as
    initial guess for the center. Maybe it would be enough to do
    just that and the fit is unnecessary. Haven`t checked that.
    '''
    max_index = np.argmax(data)
    # initial guess.
    x0 = [1.,max_index,10]
    # call to the solver
    p,_ = optimize.leastsq(my_cost, x0, args = data)
    popt.append(p)
    y.append(index)
''' 
I do transpose the data.
As a consequence the values are stored row, not columnwise.
It is often easier to store the reusults inside a loop and 
convert the data later into a numpy array.
'''
gaussian_hat = np.array(popt).T
# without the transpose, it would be center = gaussian_hat[:,1]
center = gaussian_hat[1]
y = np.array(y)

''' i do like to use an axis handle for the plot. 
Not necessary, but gives me the opportunity to add new axis if necessary.
'''
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.imshow(image)
# since it is just a plot, I can plot the x, y coordinates
ax.plot(center,y,'k-')

# fitt of a 3th order polynomial
poly = np.polyfit(y,center,3)
# evaluation at points y
x_hat = np.polyval(poly,y)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.imshow(image)
ax.plot(x_hat,y,'k-')
plt.savefig('2d_gaussian_fit.png')