import osimport numpy as npdef rgb_to_nv12(image_data: np.array): r = image_data[:, :, 0] g = image_data[:, :, 1] b = image_data[:, :, 2] y = (0.299 * r + 0.587 * g + 0.114 * b) u = (-0.169 * r - 0.331 * g + 0.5 * b + 128)[::2, ::2] v = (0.5 * r - 0.419 * g - 0.081 * b + 128)[::2, ::2] uv = np.zeros(shape=(u.shape[0], u.shape[1] * 2)) for i in range(0, u.shape[0]): for j in range(0, u.shape[1]): uv[i, 2 * j] = u[i, j] uv[i, 2 * j + 1] = v[i, j] y = y.astype(np.uint8) uv = uv.astype(np.uint8) # Return separately return y, uv if __name__ == '__main__': image_data = np.array(pil_image_data).astype(np.uint8) y, uv = rgb_to_nv12(image_data)
import sysimport numpy as npfrom PIL import Imagedef generate_nv12(input_path, output_path='./'): img = Image.open(input_path) w,h = img.size # Convert images to YUV format yuv_img = img.convert('YCbCr') y_data, u_data, v_data = yuv_img.split() # Convert Y, U, and V channel data to byte streams y_data_bytes = y_data.tobytes() u_data_bytes = u_data.resize((u_data.width // 2, u_data.height // 2)).tobytes() v_data_bytes = v_data.resize((v_data.width // 2, v_data.height // 2)).tobytes() # Arrange the UV data in the form of UVUVUVUV... uvuvuv_data = bytearray() for u_byte, v_byte in zip(u_data_bytes, v_data_bytes): uvuvuv_data.extend([u_byte, v_byte]) # y data y_path = output_path + "_y.bin" with open(y_path, 'wb') as f: f.write(y_data_bytes) # uv data uv_path = output_path + "_uv.bin" with open(uv_path, 'wb') as f: f.write(uvuvuv_data) nv12_data = y_data_bytes + uvuvuv_data # Save as NV12 format file nv12_path = output_path + "_nv12.bin" with open(nv12_path, 'wb') as f: f.write(nv12_data) # Input for the hbir model y = np.frombuffer(y_data_bytes, dtype=np.uint8).reshape(1, h, w, 1).astype(np.uint8) uv = np.frombuffer(uvuvuv_data, dtype=np.uint8).reshape(1, h//2, w//2, 2).astype(np.uint8) return y, uvif __name__ == "__main__": if len(sys.argv) < 3: print("Usage: python resize_image.py <input_path> <output_path>") sys.exit(1) input_path = sys.argv[1] output_path = sys.argv[2] y, uv = generate_nv12(input_path, output_path)