按行或列读RAW图像并显示

    科技2022-08-22  108

    按行或列读RAW图像并显示

    任务描述:

    设计一函数,该函数对K个M*N的灰度图像(矩阵)处理。功能是取每个图像的第X行(或列),生成一新的图像。要求用指针实现上述程序。

    代码实现:

    读取图像:

    #include <fstream> #include <iostream> #include <cmath> using namespace std; #define width 512 #define height 512 #define num 512 int main(){ unsigned short *data; //unsigned表示无符号类型,short表示短整形 unsigned short *data_new; int L = width * height * num; //源文件为512*512*512大小 int L_new = width * num; //新生成图片大小为512*512 data = new unsigned short[L]; //存储源文件 data_new = new unsigned short[L_new]; //存储新生成图片 ifstream infile; //以读模式打开文件 infile.open("D:\\data\\白蚁-CNU008269-head 512x512x512-ushort.raw",ios::binary); //将图片以二进制形式打开 infile.read((char*)data,L * sizeof(unsigned short)); // data的首地址指针为char类型,data的字节大小为L个单位的unsigned short型 infile.close(); //关闭文件 cout << "输入所选行数(>0)或列数(<0):" << endl; int n; cin >> n; if (n>=0){ //当输入数值大于0时表示取第n行 int a = (n-1) * height; //第n行第1个元素前有n-1行 for (int i=0;i<num;i++){ //取512*512*512中每张图片 for (int j=0;j<width;j++){ //取每张图片中固定一行中的每个元素 *(data_new + j + width * i) = *(data + a + L_new * i + j); //将所取元素的指针传给新生成图片的指针 } } } else{ int b = abs(n); for (int k=0;k<L;k++){ //对源文件中每个位置的元素进行遍历 if (k % width == b){ //取余值即为在原图中的列数 int t = k/width; //位置值除以图片宽度值取整,结果为在新图中位置 *(data_new + t) = *(data + k); //将所取元素的指针传给新生成图片的指针 } } } ofstream outfile; //以写模式打开文件 outfile.open("D:\\pythonProject\\pic_new.raw",ios::binary); outfile.write((char*)data_new,L_new * sizeof(unsigned short)); //将所生成结果写入新文件,首地址指针为char类型,data_new的字节大小为L_new个单位的unsigned short型 outfile.close(); delete[] data; delete[] data_new; return 0; }

    显示图像:

    import cv2 import numpy as np # 首先确定原图片的基本信息:数据格式,行数列数,通道数 rows=512#图像的行数 cols=512#图像的列数 channels =1# 图像的通道数,灰度图为1 # 利用numpy的fromfile函数读取raw文件,并指定数据格式 img=np.fromfile('pic_new.raw', dtype='uint16') # 利用numpy中array的reshape函数将读取到的数据进行重新排列。 img=img.reshape(rows, cols, channels) # 展示图像 cv2.imshow('ans',img) cv2.waitKey() cv2.destroyAllWindows() print('ok')

    结果示例:

    第200行:

    第200列:

    Processed: 0.018, SQL: 9