我一直在嘗試將 BGR 捕獲的幀轉換為 YUYV 格式。
在 OpenCV Python 中,我可以使用COLOR_YUV2BGR_YUY2轉換代碼將 YUYV 轉換為 BGR,但我不能執行此操作的相反操作(此操作沒有轉換代碼,我已經嘗試過,COLOR_BGR2YUV但沒有正確轉換)。我很好奇如何將 3 通道 BGR 幀轉換為 2 通道 YUYV 幀。
在這里您可以看到我用來更改相機模式以捕獲 YUYV 并將其轉換為 BGR 的代碼,我正在尋找替代品,cap.set(cv2.CAP_PROP_CONVERT_RGB, 0)以便我可以捕獲 BGR 并將其轉換為 YUYV cap.set(cv2.CAP_PROP_CONVERT_RGB, 0)(因為它是一個可選的捕獲設定和 Windows DirectShow 忽略此標志)
import cv2
import numpy as np
cap = cv2.VideoCapture(4)
_, frame = cap.read()
cap.set(cv2.CAP_PROP_CONVERT_RGB, 0) # How to replace this line with another BGR to YUYV conversion?
_, frame_rgb_off = cap.read()
bgr_cvt = cv2.cvtColor(frame_rgb_off, cv2.COLOR_YUV2BGR_YUY2)
這是顯示幀內容的除錯器輸出:
鏈接到螢屏截圖
我試圖了解 YUYV 格式,但它只有 2 通道,并且下采樣程序非常復雜。我已經檢查了 YUYV 到 BGR 的轉換方法,但我找不到數學轉換方法(解決方案通常使用命令列中的 ffmpeg 實用程式,但我認為我需要使用 numpy 陣列進行數學計算)
uj5u.com熱心網友回復:
您可以使用以下代碼將影像轉換為 YUV,然后從 YUV 創建 YUYV。在這個例子中,一個影像作為程式的輸入:
import cv2
import numpy as np
# Load sample image
img_bgr = cv2.imread("home.jpg")
cv2.imshow("original", img_bgr)
cv2.waitKey(0)
# Convert from BGR to YUV
img_yuv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2YUV)
# Converting directly back from YUV to BGR results in an (almost) identical image
img_bgr_restored = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
cv2.imshow("converted", img_bgr_restored)
cv2.waitKey(0)
diff = img_bgr.astype(np.int16) - img_bgr_restored
print("mean/stddev diff (BGR => YUV => BGR)", np.mean(diff), np.std(diff))
# Create YUYV from YUV
y0 = np.expand_dims(img_yuv[...,0][::,::2], axis=2)
u = np.expand_dims(img_yuv[...,1][::,::2], axis=2)
y1 = np.expand_dims(img_yuv[...,0][::,1::2], axis=2)
v = np.expand_dims(img_yuv[...,2][::,::2], axis=2)
img_yuyv = np.concatenate((y0, u, y1, v), axis=2)
img_yuyv_cvt = img_yuyv.reshape(img_yuyv.shape[0], img_yuyv.shape[1] * 2,
int(img_yuyv.shape[2] / 2))
# Convert back to BGR results in more saturated image.
img_bgr_restored = cv2.cvtColor(img_yuyv_cvt, cv2.COLOR_YUV2BGR_YUYV)
cv2.imshow("converted", img_bgr_restored)
cv2.waitKey(0)
diff = img_bgr.astype(np.int16) - img_bgr_restored
print("mean/stddev diff (BGR => YUV => YUYV => BGR)", np.mean(diff), np.std(diff))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395836.html
上一篇:計算單個物件的物件子陣列的總和
