传递给线程时,总结numpy.ndarray失败

时间:2016-02-12 07:38:53

标签: python arrays multithreading numpy

我正在编写一个Python脚本,通过调用ctypes与帧抓取器连接。它从帧抓取器获取图像作为指向字节数组的指针。然后,我想沿着其中一个维度对数组求和以绘制轮廓。当我在同一个线程中执行此操作时,此工作正常。但我想交给另一个线程进行处理(所以我可以尽快抓取图像)。当我这样做时,numpy.sum方法似乎在内部无声溢出,因为我得到的配置文件中有负数。知道这里可能会发生什么吗?这是一段代码片段:

self.grablib.IC_SnapImage(self.hGrabber, 100) # 100 ms timeout
imgPtr = self.grablib.IC_GetImagePtr(self.hGrabber)
#imgPtr is returned as a char pointer, which will mess things up
imgPtr2 = ctypes.cast(imgPtr, ctypes.POINTER(ctypes.c_byte))
imgArray = np.ctypeslib.as_array(imgPtr2, (572, 768))
imgTime = datetime.now()
args = (imgArray, imgTime)
Thread(target=self.processImage, args=args).start()

这是处理线程中的违规代码:

# Another thread to actually do the processing, while the previous one gets another image
def processImage(self, imgArray, imgTime):
    iy = np.sum(imgArray[range(0, 572, 2)], 1, dtype=np.float)

我在dtype中作为sum参数放置似乎并不重要,溢出仍然发生。这就好像numpy的累加器默认为错误的类型,并且没有被dtype参数推翻。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所建议的那样,错误是向POINTER(ctypes.c_byte)投射了一个字符指针。显然c_byte已签署,这是混乱的起因。基本上我的脚本加了一大堆负数。对不起,这次不是你的错!违规行应该是:

imgPtr2 = ctypes.cast(imgPtr, ctypes.POINTER(ctypes.c_uint8))

显然uint8是一个无符号的8位整数,这正是我想要的。我不知道为什么我没有把它开始。 (另外,我不知道为什么它只是在一个不同的线程中工作 - 这很奇怪。)