Python:线程 + curve_fit:内部例程的空参数

0 投票
1 回答
1357 浏览
提问于 2025-04-17 23:40

我在使用以下代码时遇到了一些问题,这段代码本来是用来通过线程进行高斯拟合的:



    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.#

如果我只运行一个线程而不是两个,程序就能正常工作,但我不知道我哪里出错了。谢谢你的帮助。

1 个回答

1

我认为leastsq()这个函数在多线程环境下不安全,也就是说,如果你在多个线程同时使用它,可能会出现问题。为了避免这种情况,你需要在调用curve_fit()的时候加上一个线程锁(threading.Lock()),但这样可能会影响你原本的目的。另一种选择是使用多进程(multiprocessing)。

撰写回答