將圖片轉(zhuǎn)為coe文件的matlab代碼
其實這個是我讓ai寫的,我也不知道算不算原創(chuàng)。將圖片中RGB888轉(zhuǎn)為RGB565,采用的是取高位的方式。
clc; clear all;
% 讀取圖片
img = imread('your_image.jpg'); % 替換 'your_image.jpg' 為您的圖片文件名
% 獲取圖片尺寸
[height, width, ~] = size(img);
% 初始化字符串數(shù)組(一列)
data = strings(height * width, 1);
% 轉(zhuǎn)換每個像素的 RGB 數(shù)據(jù)為字符串
index = 1;
for row = 1:height
? ? for col = 1:width
? ? ? ? r = bitshift(img(row, col, 1), -3); % 提取紅色高5位,右移3位
? ? ? ? g = bitshift(img(row, col, 2), -2); % 提取綠色高6位,右移2位
? ? ? ? b = bitshift(img(row, col, 3), -3); % 提取藍色高5位,右移3位
? ? ? ??
? ? ? ? % 合并三組數(shù)據(jù)為一個 16 位二進制數(shù),并轉(zhuǎn)換為 16 進制字符串
? ? ? ? rgb_combined = bitor(bitor(bitshift(uint16(r), 11), bitshift(uint16(g), 5)), uint16(b));
? ? ? ? hex_str = sprintf('%04X', rgb_combined);
? ? ? ??
? ? ? ? % 存儲結(jié)果到 data 變量
? ? ? ? data(index) = hex_str;
? ? ? ? index = index + 1;
? ? end
end
% 將數(shù)據(jù)寫入 .coe 文件
fileID = fopen('output.coe', 'w');
fprintf(fileID, 'memory_initialization_radix = 16;\n');
fprintf(fileID, 'memory_initialization_vector =\n');
for i = 1:numel(data)
? ? fprintf(fileID, '%s\n', data(i)); % 添加回車,每個數(shù)據(jù)獨占一行
end
fprintf(fileID, ';\n'); % 添加最后一行分號
fclose(fileID);
disp('數(shù)據(jù)已寫入 output.coe 文件。');