如何使用kinect v2相机—pykinect2

1、如何使用Kinect v2.0的相机

第一步:链接好点击的线。接线图如下所示。

        连接好之后我们的信息提示灯应该是白色的。

        黄色的是连接失败的。

2、下载微软提供的sdk包

  下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=44561

  下载方式直接点击下载:直接点击 安装在c盘默认

  直接安装产生三个exe文件。

3、如何使用相机

        我们的相机必须要使用的是USB3.0的连接方式,USB2.0不可以我的笔记本就是不可以的,我的台式小机箱就是可以的。

        参考文章 配合opencv 和 我们的相机的代码:

        代码的连接地址为:

        https://blog.csdn.net/qq_43259383/article/details/107727519?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522171800372916800186584907%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=171800372916800186584907&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-25-107727519-null-null.142^v100^pc_search_result_base7&utm_term=kinect%20v2%20windows%E4%B8%8B%E4%BD%BF%E7%94%A8&spm=1018.2226.3001.4187

4、下载opencv

  如何下载opencv

        一个博客教你怎么下载opencv以及如何安装

        https://blog.csdn.net/shuiyixin/article/details/105998661

  在哪个网站下载opencv

        opencv的安装地址 网站:https://opencv.org/releases/page/3/

        我们选择安装的版本为4.3.0

  采用什么方式安装opencv

        我们安装的opencv的教程:https://blog.csdn.net/weixin_40323532/article/details/137992134?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522171833036916777224474590%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=171833036916777224474590&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-137992134-null-null.142^v100^pc_search_result_base7&utm_term=opencv%E5%A6%82%E4%BD%95%E5%AE%89%E8%A3%85&spm=1018.2226.3001.4187

  测试我的opencv安装以及配置是否正确。

        测试代码,测试我安装的是否正确,测试代码的地址:

        https://blog.csdn.net/qq_43259383/article/details/107727519?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522171800372916800186584907%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=171800372916800186584907&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-25-107727519-null-null.142^v100^pc_search_result_base7&utm_term=kinect%20v2%20windows%E4%B8%8B%E4%BD%BF%E7%94%A8&spm=1018.2226.3001.4187

5、再次测试成功

        我们使用kinect实现测试传感器的远近。

        代码如下所示:

// Standard Library(头文件)
#include <iostream>
#include <opencv.hpp>
// Kinect for Windows SDK Header
#include <Kinect.h>

using namespace cv;
using namespace std;

int main()
{
	IKinectSensor* pSensor = nullptr;//换一个简单一点的理解方式,定义一个IKinectSensor类,pSensor就是给传感器取的一个名字
	GetDefaultKinectSensor(&pSensor);//GetDefaultKinectSensor是取得默认传感器,门
	pSensor->Open();//开启传感器,开门


	IDepthFrameSource* pFrameSource = nullptr;//定义一个IDepthFrameSource类,pFrameSource就是给深度图像取的一个名字
	pSensor->get_DepthFrameSource(&pFrameSource);//从pSensor传感器中得到深度图像来源传到pFrameSource中,门的地址


	IDepthFrameReader* pFrameReader = nullptr;
	pFrameSource->OpenReader(&pFrameReader);//同上,将pFrameSource的值传到pFrameReader,从门的地址中得到信息的接口


	//size_t uFrameCount = 0;
	while (1)//进入循环
	{

		double time0 = static_cast<double>(getTickCount());//记录起始时间

		// 4a. Get last frame
		IDepthFrame* pFrame = nullptr;
		if (pFrameReader->AcquireLatestFrame(&pFrame) == S_OK)//通过接口来取得信息
		{
			//尝试把这个放到循环外面
			int iWidth = 0;
			int iHeight = 0;
			IFrameDescription* pFrameDescription = nullptr;//IFrameDescription类,可以读取里面包含的画面的基本信息(高、宽、像素的大小等等)
			pFrame->get_FrameDescription(&pFrameDescription);//从pFrame中取得信息传给pFrameDescription
			pFrameDescription->get_Width(&iWidth);//取得宽度
			pFrameDescription->get_Height(&iHeight);//取得高度
			pFrameDescription->Release();//用完就释放
			pFrameDescription = nullptr;//指向空


			UINT uBufferSize = 0;//UINT类型在WINDOWS API中有定义,它对应于32位无符号整数
			UINT16* pBuffer = nullptr;
			pFrame->AccessUnderlyingBuffer(&uBufferSize, &pBuffer);
			//AccessUnderlyingBuffer类,可以取得画面数据的指针(pBuffer)、以及数据数组的大小(iBufferSize)
			//pBuffer 是一个UINT16的指标,他所指到的数组、就是整张图的数据了


			int x = iWidth / 2,
				y = iHeight / 2;//这个换算是怎么来的?
			size_t idx = x + iWidth * y;
			std::cout << pBuffer[idx] << std::endl;

			//小玩意
			if (pBuffer[idx] < 600)
			{
				system("color 4F");
			}
			else { system("color 0F"); }//距离低于一定的时候改变窗口颜色


			// 4e. release frame
			pFrame->Release();
			pFrame = nullptr;
			//++uFrameCount;
		}
		else
		{
			cout << "出错" << endl;
			//break;
		}
		time0 = ((double)getTickCount() - time0) / getTickFrequency();
		cout << "运行时间为:" << time0 << "秒" << endl;

	}
	waitKey(1000000);

	// 3b. release frame reader
	pFrameReader->Release();
	pFrameReader = nullptr;
	// 2b. release Frame source
	pFrameSource->Release();
	pFrameSource = nullptr;
	// 1c. Close Sensor
	pSensor->Close();
	// 1d. Release Sensor
	pSensor->Release();
	pSensor = nullptr;
	return 0;
}

6、使用人家大佬弄好的sdk-pykinect2。

案例地址:https://github.com/Kinect/PyKinect2

具体配置方法:https://blog.csdn.net/qq_28586501/article/details/130338369

第一步:

安装
numpy pip install numpy 
安装cv
 pip install opencv-python 
安装open3d: 
pip install open3d 安装pykinect2 pip install pykinect2

第二步:

1、PykinectV2:
 把 assert sizeof(tagSTATSTG) == 72, sizeof(tagSTATSTG) 修改为 assert sizeof(tagSTATSTG) == 80, sizeof(tagSTATSTG) //2216行 
把下面的东西注释掉 from comtypes import _check_version; _check_version('')

第三步:

2、PykinectRuntime: 将time.clock()改为time.perf_counter()。 因为3.8以后就不支持time.clock()

7、采集我们自己的图像以及深度图。

代码如下所示。

# time:2024.10.1
# by:冒险岛岛主

import pygame
from pykinect2 import PyKinectV2, PyKinectRuntime
import ctypes
import numpy as np

# 初始化 pygame
pygame.init()

# 设置初始窗口大小,可以手动调整此大小
screen_width, screen_height = 960 * 2, 540  # 原始大小缩小一半,方便显示
screen = pygame.display.set_mode((screen_width, screen_height), pygame.RESIZABLE)

# 初始化 Kinect,启用 RGB 和深度帧
kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Color | PyKinectV2.FrameSourceTypes_Depth)

# 定义主循环标志
done = False
clock = pygame.time.Clock()

# 当前窗口尺寸
current_width, current_height = screen.get_size()

# 初始化缩放的 surface 以避免变量未定义的错误
scaled_color_surface = pygame.Surface((1, 1))  # 用一个小的表面做占位符
scaled_depth_surface = pygame.Surface((1, 1))  # 同样是占位符

while not done:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.VIDEORESIZE:
            # 更新窗口尺寸
            current_width, current_height = event.size
            screen = pygame.display.set_mode((current_width, current_height), pygame.RESIZABLE)

    # 计算图像显示区域的缩放比例,保持等比例缩放
    scale_factor = min(current_width // 2 / 1920, current_height / 1080)  # 两个图像各占窗口的一半

    # 如果有新的视频帧可用(RGB)
    if kinect.has_new_color_frame():
        try:
            # 获取颜色帧数据
            color_frame = kinect.get_last_color_frame()
            color_frame = color_frame.reshape((1080, 1920, 4))  # RGB 图像 1080p, BGRA 格式
            color_frame = color_frame[:, :, [2, 1, 0]]  # 转换为 RGB
            color_surface = pygame.surfarray.make_surface(color_frame.swapaxes(0, 1))

            # 按比例缩放 RGB 图像
            scaled_color_surface = pygame.transform.scale(
                color_surface, (int(1920 * scale_factor), int(1080 * scale_factor)))
        except:
            print("Error processing RGB frame")
            # 在捕获异常时,不要更新 scaled_color_surface

    # 如果有新的深度帧可用
    if kinect.has_new_depth_frame():
        try:
            # 获取深度帧数据
            depth_frame = kinect.get_last_depth_frame()
            depth_frame = depth_frame.reshape((424, 512))  # 深度图像 424x512

            # 将深度值归一化到 0-255 之间用于显示
            depth_frame = np.uint8(depth_frame.clip(500, 4500) / 4500 * 255)  # 剪裁并缩放深度范围

            # 将单通道扩展为三通道
            depth_frame = np.repeat(depth_frame[:, :, np.newaxis], 3, axis=2)

            # 将深度图像缩放到 1920x1080,然后再按比例缩放
            depth_frame_surface = pygame.surfarray.make_surface(depth_frame.swapaxes(0, 1))
            scaled_depth_surface = pygame.transform.scale(
                depth_frame_surface, (int(1920 * scale_factor), int(1080 * scale_factor)))
        except:
            print("Error processing Depth frame")
            # 在捕获异常时,不要更新 scaled_depth_surface

    # 绘制 RGB 图像在左边
    screen.blit(scaled_color_surface, (0, 0))

    # 绘制深度图像在右边
    screen.blit(scaled_depth_surface, (int(current_width / 2), 0))

    # 更新显示
    pygame.display.update()

    # 控制帧率
    clock.tick(60)

# 退出程序
kinect.close()
pygame.quit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值