gpt4 book ai didi

python - 传递给线程时求和 numpy.ndarray 失败

转载 作者:太空宇宙 更新时间:2023-11-03 16:56:56 24 4
gpt4 key购买 nike

我正在编写一个 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)

无论我将什么作为 sum 中的 dtype 参数,溢出仍然会发生。就好像 numpy 的累加器默认为错误的类型,并且没有被 dtype 参数覆盖。

最佳答案

正如我在评论中所建议的,错误是将 char 指针转换为 POINTER(ctypes.c_byte)。显然 c_byte 是有符号的,这就是引起困惑的地方。基本上我的脚本是添加大量负数。对不起numpy,这次不是你的错!有问题的行应该是:

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

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

关于python - 传递给线程时求和 numpy.ndarray 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com