Python:threading+;曲线拟合:内部例程的空参数
我在使用以下代码时遇到了一些问题,这些代码应该使用线程进行高斯拟合:Python:threading+;曲线拟合:内部例程的空参数,python,multithreading,class,curve-fitting,python-multithreading,Python,Multithreading,Class,Curve Fitting,Python Multithreading,我在使用以下代码时遇到了一些问题,这些代码应该使用线程进行高斯拟合: from PIL import Image import numpy as np from scipy.optimize import curve_fit import threading class myThread (threading.Thread): def __init__(self, index): threading.Threa
from PIL import Image
import numpy as np
from scipy.optimize import curve_fit
import threading
class myThread (threading.Thread):
def __init__(self, index):
threading.Thread.__init__(self)
self.index = index
def run(self):
for i in np.arange(n_Bild.shape[1]):
curve_fit(self.gauss, x_x, Intensitaet[self.index, ...], p0=(Intensitaet[self.index, i], i, 1, 0))
def gauss(self, x, a, b, c, d):
return a * np.exp(-(x-b) ** 2 / (2 * c ** 2)) + d
Bild = Image.open("test.bmp")
n_Bild = np.asarray(Bild)
Intensitaet = np.zeros((n_Bild.shape[0], n_Bild.shape[1]), dtype=np.uint32)
Intensitaet += n_Bild[..., ..., 0]
Intensitaet += n_Bild[..., ..., 1]
Intensitaet += n_Bild[..., ..., 2]
x_x = np.arange(n_Bild.shape[1]) #Pixel auf "x"-Achse
threads = []
# Create new threads
thread0 = myThread(0)
thread1 = myThread(1)
# Add threads to thread list
threads.append(thread0)
threads.append(thread1)
# Start new Threads
thread0.start()
thread1.start()
# Wait for all threads to complete
for t in threads:
t.join()
print "finished"
如果我运行我的程序,我会得到一个错误:
SystemError: null argument to internal routine
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Anaconda\lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "G:/DropBox/Daten/Dropbox/Uni/Bachelorarbeit/Python/ThreadTest.py", line 12, in run
curve_fit(self.gauss, x_x, Intensitaet[self.index, ...], p0=(Intensitaet[self.index, i], i, 1, 0))
File "C:\Anaconda\lib\site-packages\scipy\optimize\minpack.py", line 533, in curve_fit
res = leastsq(func, p0, args=args, full_output=1, **kw)
File "C:\Anaconda\lib\site-packages\scipy\optimize\minpack.py", line 378, in leastsq
gtol, maxfev, epsfcn, factor, diag)
error: Internal error constructing argument list.#
如果我只运行一个线程而不是两个线程,程序运行得很好,但我不知道我做错了什么。
感谢您的帮助。我认为leastsq()不是线程安全的,您需要在调用curve_fit()时使用threading.Lock()或使用多处理 无论如何都应该使用
多处理
,因为多亏了GIL
,python线程只在I/O绑定的情况下有用。事实上,在这种情况下,如果leastsq
在C端做了一些非琐碎的事情,它就会绕过GIL(因为它在C端时可以释放)。我对leastsq
的内部功能还不太熟悉,无法判断它在调用剩余计算回调之前是否做了很多工作,但如果它做了,那么可以说它肯定是绕过GIL的候选对象。