如何用Python3 OpenCV将640x480的RAW YUYV422帧转为RGB?
Hey there, let's tackle this YUYV422 to RGB conversion issue in OpenCV Python step by step. I've run into similar headaches before, so here's what you need to check and fix:
First, Verify Your RAW Data Loading
First off, make sure you're loading the 640x480 YUYV422 raw data correctly. YUYV422 is a packed format where each pair of pixels uses 4 bytes (Y0, U0, Y1, V0), so the total size of your raw frame should be 6404802 bytes (since each pixel averages 2 bytes). If your data isn't the right size, everything after that will fail.
Check this with a quick snippet:
import numpy as np # Load your raw YUYV data (adjust the path/loading method to match your source) raw_data = np.fromfile("your_frame.raw", dtype=np.uint8) expected_size = 640 * 480 * 2 if raw_data.size != expected_size: print(f"Error: Raw data size is {raw_data.size}, expected {expected_size}") else: print("Raw data size checks out!")
Use the Correct OpenCV Color Conversion Code
OpenCV has specific flags for YUYV formats. The right one for YUYV422 (also called YUY2) is cv.COLOR_YUV2RGB_YUYV (note the suffix _YUYV at the end—this is easy to mix up!).
Here's a complete conversion snippet:
import cv2 import numpy as np # Load raw data raw_data = np.fromfile("your_frame.raw", dtype=np.uint8) # Reshape into 640x480 frame in YUYV422 format yuyv_frame = raw_data.reshape((480, 640, 2)) # Convert to RGB rgb_frame = cv2.cvtColor(yuyv_frame, cv2.COLOR_YUV2RGB_YUYV) # Optional: Display to verify cv2.imshow("RGB Frame", rgb_frame) cv2.waitKey(0) cv2.destroyAllWindows()
Common Mistakes That Cause Errors
- Wrong reshape dimensions: Make sure you're reshaping to
(height, width, 2)—not(width, height, 2). OpenCV uses row-major (height first) order. - Incorrect data type: YUYV data is 8-bit unsigned, so use
np.uint8when loading. Using any other dtype will break the conversion. - Mixing up color conversion flags: Avoid using
cv.COLOR_YUV2RGBwithout the_YUYVsuffix—that's for planar YUV formats, not packed YUYV422. - Truncated or corrupted raw data: If your raw file is missing bytes or got corrupted during capture/saving, the conversion will throw errors. Double-check your data source (e.g., camera SDK, file write process).
If You're Still Getting Errors...
If you updated your code based on comments and still see issues, share the exact error message you're getting (e.g., "error: (-215:Assertion failed) ...") and a bit more context about how you're acquiring the raw YUYV data (camera SDK, file source, etc.). That will help narrow down the problem faster!
内容的提问来源于stack exchange,提问作者PhilBot

