c++利用opencv显示raw遥感图像,摸索了一天了,记录一下吧,总之就是利用fopen打开,然后memcpy拷贝内存,一定要注意原始图像的分辨率,还有数据的类型!
/***********************************************************
打开raw图像,并在opencv中显示。需要知道原始图像的分辨率 (8221*7441);
和数据类型为 float,利用fopen和memcpy内存拷贝赋值到opencv中并显示!!!
@zhou 2020/1/8
************************************************************/
#include
#include
using namespace std;
using namespace cv;
int main()
{
int height = 7441;//原始图像的高
int width = 8221;//原始图像的宽
/*int height = 7441;
int width = 8221;*/
FILE *fp = NULL; //定义指针
fp = fopen("1.raw", "rb+");
float *data = (float *)malloc(width*height * sizeof(float)); //内存分配,new,malloc都行
fread(data, sizeof(float), width*height, fp); //在缓存中读取数据
cv::Mat img;
int bufLen = width*height; //定义长度
img.create(height, width, CV_32FC1);//创建Mat
memcpy(img.data, data, bufLen * sizeof(float)); //内存拷贝
/*
//遍历图像的每个像素点
for (int row = 0; row < img.rows; row++)
{
for (int col = 0; col < img.cols; col++)
{
int d = img.at(row, col);
printf("%d,%d,的值为:%d\n", row, col, d);
}
}
*/
//图像(3678,535)处的像素值
int pixel = img.at(3678, 635);
printf("%d,%d,的像素值为:%d\n", 3678, 635, pixel);
//normalize(img,img, 1.0,255.0, NORM_INF);
double minv = 0.0, maxv = 0.0;
double* minp = &minv;
double* maxp = &maxv;
minMaxIdx(img, minp, maxp);//找到最大和最小的像素值
cout << "最大的像素值为:" << *minp << endl;
cout << "最大的像素值为:" << *maxp << endl;
//img.convertTo(img, CV_8UC1, 255, 0); //归一化为0,255
namedWindow("img", 0);//窗口可以缩放
imshow("img", img); //显示
//imwrite("out.jpg", img); //保存为jpg
waitKey(0);
return 0;
}
运行结果如下:
补充python版本,用numpy打开很方便,代码如下:
"""
python 打开raw图像并显示
@zhou 2020/1/8
"""
import numpy as np
import cv2
img = np.fromfile('1.raw',dtype=np.float32)
img=img.reshape((7441,8221))
cv2.namedWindow("zhou",0)
cv2.imshow("zhou",img)
cv2.waitKey(0)
同样结果如下: