跳转至

功能及代码

用户输入图像路径、新宽度、新高度。输出16进制图像数据

程序主要用在串口传图方面。

```python main.py import cv2 import numpy as np

def convert_to_rgb332(img): # 取R高3位, {5'b0, R[7:5]} R = np.right_shift(img[:, :, 2], 5) # 取G高3位, {5'd0, G[7:5]} G = np.right_shift(img[:, :, 1], 5) # 取B高2位, {6'd0, B[7:6]} B = np.right_shift(img[:, :, 0], 6)

# 拼接 {R[7:5], G[7:5], B[7:6]}
rgb332 = (R << 5) + (G << 2) + B
return rgb332

def save_hex_data(data, filename): # 将数据以十六进制形式保存到文本文件 with open(filename, 'w') as f: for value in data.flatten(): f.write(f'{value:02x} ') # 使用格式化字符串将整数转换为两位十六进制数

def process_image(image_path, new_width, new_height): # 读取图像 img = cv2.imread(image_path) if img is None: print("Image not found. Please check the image path.") return None img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换为RGB格式

# 调整图像大小
img = cv2.resize(img, (new_width, new_height))
return img

图片路径和尺寸

image_path = r"C:\Users\Administrator\Desktop\5fcf95f976f3998469e9338e61d351f.jpg" new_width = 100 new_height = 100

处理图像

img = process_image(image_path, new_width, new_height) if img is not None: # 转换为RGB332格式 rgb332 = convert_to_rgb332(img)

# 将rgb332数据以十六进制形式保存到文本文件
save_hex_data(rgb332, 'rgb332.txt')

```

参考链接

串口传图:RGB332格式和RGB565格式