opencv操作raw文件

x33g5p2x  于2022-06-08 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(498)

python版:

import numpy as np
import cv2
height=480
width=640
channels=3
# img = cv2.imread('data/04/04(1).bmp')
# # 这里需要我们在当前目录下放一张名为cat.jpg的文件
# img.tofile('04(1).raw')
# #利用numpy中array的函数tofile将数据写入文件
# #这时我们发现当前目录下新增了一个文件,名为cat.raw
# # 我们先确定原图片的数据格式和大小,通道数,否者无法进行下一步转换
# type = img.dtype#得到数据格式,如uint8和uint16等
# height,width, channels = img.shape# 得到图像大小和通道数
# 利用numpydefromfile函数读取raw文件,并指定数据格式
imgData = np.fromfile(r'C:\Users\Administrator\Documents\tmp\ceshia\ceshia\1648629378140_0.7237443_rgb.raw', dtype=np.uint8)
# 利用numpy中array的reshape函数将读取到的数据进行重新排列。
imgData = imgData.reshape(height,width,channels)

imgData=cv2.cvtColor(imgData,cv2.COLOR_BGR2RGB)
to_dir=r'C:\Users\Administrator\Documents\tmp\ceshia\ceshia'

cv2.imwrite(to_dir+"jia.jpg",imgData)
# 展示图像
cv2.imshow('img',imgData)
# 注意到这个函数只能显示uint8类型的数据,如果是uint16的数据请先转成uint8。否则图片显示会出现问题。**
cv2.waitKey()

c++版:

#include<iostream>
#include<opencv2/opencv.hpp>
#include<fstream>
using namespace std;
using namespace cv;

int main()
{
    // open raw data
    const std::string file_path = "D:/E_Dragon/OPENCV/testpictures/1.raw";
    std::ifstream fin;
    // 注意,这里要指定binary读取模式
    fin.open(file_path, std::ios::binary);
    if (!fin) {
        std::cerr << "open failed: " << file_path << std::endl;
    }
    // seek函数会把标记移动到输入流的结尾
    fin.seekg(0, fin.end);
    // tell会告知整个输入流(从开头到标记)的字节数量
    int length = fin.tellg();
    // 再把标记移动到流的开始位置
    fin.seekg(0, fin.beg);
    std::cout << "file length: " << length << std::endl;

    // load buffer
    char* buffer = new char[length];
    // read函数读取(拷贝)流中的length各字节到buffer
    fin.read(buffer, length);

    // construct opencv mat and show image
    cv::Mat image(cv::Size(720, 540), CV_8UC1, buffer);
    cv::imshow("test", image);
    cv::waitKey();
}

原文链接:https://blog.csdn.net/weixin_51229250/article/details/119789057

相关文章

微信公众号

最新文章

更多