from hbdk4.compiler import load, Hbm
import numpy as np
from PIL import Image
def generate_nv12(img):
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])
# Input for the hbir model
y = np.frombuffer(y_data_bytes, dtype=np.uint8).reshape(1, h, w, 1).astype(np.uint8)
# np.save("y_data.npy", y)
uv = np.frombuffer(uvuvuv_data, dtype=np.uint8).reshape(1, h//2, w//2, 2).astype(np.uint8)
# np.save("uv_data.npy", uv)
return y, uv
def compare_arrays(array1, array2, decimal_places=2):
"""
Compare two arrays for consistency up to a specified number of decimal places.
Parameters:
- array1: First numpy array.
- array2: Second numpy array.
- decimal_places: Number of decimal places to consider for alignment.
Returns:
- are_equal: True if arrays are consistent up to the specified decimal places, False otherwise.
- max_difference: Maximum difference (absolute value) if arrays are not consistent, else 0.
"""
# Round the arrays to the specified decimal places
rounded1 = np.round(array1, decimals=decimal_places)
rounded2 = np.round(array2, decimals=decimal_places)
# Check equality
are_equal = np.array_equal(rounded1, rounded2)
# Calculate maximum difference if not equal
max_difference = 0
if not are_equal:
max_difference = np.max(np.abs(array1 - array2))
return are_equal, max_difference
hbir = load("./quantized_nv12_remove_stage3.bc")
hbm = Hbm("./quantized_nv12_remove_stage3.hbm")
# Create a random image with the shape (1, 512, 960, 3)
# Generate random RGB values in the range 0-255
image_data = np.random.randint(0, 256, (512, 960, 3), dtype=np.uint8)
# Convert the numpy array to a PIL image
img = Image.fromarray(image_data)
y, uv = generate_nv12(img)
inputs = {"input_0_y": y, "input_0_uv": uv}
# 分别进行hbir和Hbm推理
hbir_outputs = hbir[0].feed(inputs)
# print("hbir_outputs:", hbir_outputs)
hbm_x86_outputs = hbm[0].feed(inputs)
# print("hbm_x86_outputs:", hbm_x86_outputs)
# 比较Hbir和hbm输出
for idx, v in enumerate(hbir[0].outputs):
hbir_data = hbir_outputs[v.name]
hbm_x86_data = hbm_x86_outputs[v.name]
# Compare arrays
are_equal, max_difference = compare_arrays(hbir_data, hbm_arrch64_data, decimal_places=4)
if not are_equal:
print("Maximum difference:", max_difference)
else:
print(f"outputs[{idx}] is equal!")
评论