c++ opencv float mat 转化为uchar mat示例

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

Mat mat_f32_2_u8()
{
	Mat im(100, 200, CV_32FC3, Scalar(100, 240, 0));
	for (int i = 0; i < im.rows; i++)
	{
		for (int j = 0; j < im.cols; j++)
		{
			im.at<cv::Vec3f>(i, j)[0] += 10.;
			im.at<cv::Vec3f>(i, j)[1] += 30.;
		}
	}
	Mat u8_im;
	im.convertTo(u8_im, CV_8UC3);//超出255截断为255
	return u8_im;
}

int main()
{
	Mat img = mat_f32_2_u8();
	imshow("test", img);
	waitKey(0);
	return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.0.0)
project(hello)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
set(SOURCE_FILES main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
message(STATUS ${OpenCV_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
光流是计算相邻两帧图像中像素点的运动信息的一种方法。在 OpenCV 中,可以使用 calcOpticalFlowPyrLK 函数来计算光流。以下是一个简单的示例代码: ```c++ #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main() { VideoCapture cap("test.mp4"); if (!cap.isOpened()) { cout << "Failed to open video" << endl; return -1; } Mat old_frame, old_gray; vector<Point2f> old_points; // 读取第一帧图像并提取角点 cap.read(old_frame); cvtColor(old_frame, old_gray, COLOR_BGR2GRAY); goodFeaturesToTrack(old_gray, old_points, 100, 0.3, 7, Mat(), 7, false, 0.04); // 创建窗口 namedWindow("Optical Flow", WINDOW_NORMAL); while (true) { Mat frame, gray; vector<Point2f> new_points; vector<uchar> status; vector<float> err; // 读取当前帧图像并转为灰度图像 cap.read(frame); if (frame.empty()) { break; } cvtColor(frame, gray, COLOR_BGR2GRAY); // 计算光流 calcOpticalFlowPyrLK(old_gray, gray, old_points, new_points, status, err); // 绘制光流 for (int i = 0; i < old_points.size(); i++) { if (status[i]) { Point2f pt1 = old_points[i]; Point2f pt2 = new_points[i]; line(frame, pt1, pt2, Scalar(0, 255, 0), 2); circle(frame, pt2, 5, Scalar(0, 0, 255), -1); } } // 显示结果 imshow("Optical Flow", frame); if (waitKey(30) == 27) { break; } // 更新先前帧的信息 old_gray = gray.clone(); old_points = new_points; } cap.release(); destroyAllWindows(); return 0; } ``` 在上面的代码中,首先读取第一帧图像并使用 goodFeaturesToTrack 函数提取角点。然后,循环读取每一帧图像,计算光流并绘制结果。最后更新先前帧的信息。在计算光流时,可以使用 calcOpticalFlowFarneback 函数实现更高级的光流计算。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值