一、下载MVS软件
按图操作直接下载安装即可
海康机器人-机器视觉-下载中心https://www.hikrobotics.com/cn/machinevision/service/download/?module=0
二、获取源码
打开你安装MVS的位置,按我这个路径打开:Development--Samples--Python
在python文件夹里有很多案例,其中GrabImage是读取工业相机视频流的实例代码
三、修改GrabImage
注意:这些都是海康自己定义的函数,反正我基本上都看不太懂,咱知道怎么用就行了没必要去细品,如果真想研究的话可以前往下方链接
传送门https://talent.hikvision.com/society/sHome
开始修改work_thread函数
直接定位到work_thread函数
print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stOutFrame.stFrameInfo.nWidth, stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nFrameNum))
这一行可以知道stOutFrame.stFrameInfo.nWidth和stOutFrame.stFrameInfo.nHeight分别可以获取到图像的宽和高
那么两者相乘就可以得到图像数据的总大小
frame_len = stOutFrame.stFrameInfo.nWidth * stOutFrame.stFrameInfo.nHeight
咨询了厂家技术他们说图像是存储在内存地址中,所以需要定义一个缓存区来接收这个地址中的图像,c_ubyte 表示一个无符号的 8 位整数(相当于 C 语言中的 unsigned char),一张图像的长度是frame_len所以buf_type就可以接收一张长度为frame_len的图像数据
buf_type = (c_ubyte * frame_len)
stOutFrame.pBufAddr是工业相机SDK返回的指针,指向的是图像数据的内存地址
addressof用于获取 stOutFrame.pBufAddr的地址
buf_type.from_address可直接访问到改地址中的数据
imgData则拿到了这张图像的数据
imgData = buf_type.from_address(addressof(stOutFrame.pBufAddr.contents))
但是imgData拿到的是一维数组所以才需要转换成二维数组才能得到行列数据
frame = np.frombuffer(imgData, dtype=np.uint8).reshape(
(stOutFrame.stFrameInfo.nHeight,
stOutFrame.stFrameInfo.nWidth))
这里拿到的二维图像数据取决于你在MVS软件中的设置的像素格式,如下图:
我这边是Bayer RG8是一种压缩后的RGB图像,如果直接cv2.imshow出来看起来就会像灰度的,所以还需要进行格式转换
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BAYER_RG2BGR)
到此就拿到RGB彩色图像啦
懒得看修改过程可以直接复制下面的代码替换自己的work_thread函数
def work_thread(cam=0, pData=0, nDataSize=0):
stOutFrame = MV_FRAME_OUT()
memset(byref(stOutFrame), 0, sizeof(stOutFrame))
while True:
ret = cam.MV_CC_GetImageBuffer(stOutFrame, 1000)
if None != stOutFrame.pBufAddr and 0 == ret:
# print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stOutFrame.stFrameInfo.nWidth, stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nFrameNum))
# nRet = cam.MV_CC_FreeImageBuffer(stOutFrame)
frame_len = stOutFrame.stFrameInfo.nWidth * stOutFrame.stFrameInfo.nHeight
buf_type = (c_ubyte * frame_len) # 定义缓冲区类型
imgData = buf_type.from_address(addressof(stOutFrame.pBufAddr.contents))
# 将一维数据转换为二维图像格式
frame = np.frombuffer(imgData, dtype=np.uint8).reshape(
(stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nWidth))
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BAYER_RG2BGR)
cv2.imshow("rgb_image", rgb_image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
print ("no data[0x%x]" % ret)
if g_bExit == True:
break
四、再次提醒!
个人不建议太深入研究海康的源码,会用就行!会用就行!
实在有这方面的需求的话,再次送上传送门: