我使用此代碼將黑白影像插入彩色影像,沒關系:
face_grey = cv.cvtColor(face, cv.COLOR_RGB2GRAY)
for row in range(0, face_grey.shape[0]):
for column in range(face_grey.shape[1]):
img_color[row 275][column 340] = face_grey[row][column]
plt.imshow(img_color)
但是,當我嘗試使用此代碼將彩色影像插入黑白影像時,出現錯誤:
img_gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
for row in range(0, face.shape[0]):
for column in range(face.shape[1]):
img_gray[row 275][column 340] = face[row][column]
plt.imshow(img_gray)
TypeError: only size-1 arrays can be converted to Python scalars
ValueError: setting an array element with a sequence.
uj5u.com熱心網友回復:
彩色影像需要 3 個通道來表示紅色、綠色和藍色分量。
灰度影像只有一個通道 - 灰色。
您不能將 3 通道影像放入 1 通道影像中,就像您不能將 3 針插頭插入單孔插座一樣。
您需要先將您的灰度影像提升為 3 個相同的通道:
background = cv2.cvtColor(background, cv2.COLOR_GRAY2BGR)
例子:
# Make grey background, i.e. 1 channel
background = np.full((200,300), 127, dtype=np.uint8)
# Make small colour overlay, i.e. 3 channels
color = np.random.randint(0, 256, (100,100,3), dtype=np.uint8)
# Upgrade background from grey to BGR, i.e. 1 channel to 3 channels
background = cv2.cvtColor(background, cv2.COLOR_GRAY2BGR)
# Check its new shape
print(background.shape) # prints (200, 300, 3)
# Paste in small coloured image
background[10:110, 180:280] = color

uj5u.com熱心網友回復:
彩色影像具有三個顏色通道 rgb 的形狀 (n,m,3)。當顏色資訊被丟棄時,灰度影像有恥辱(n,m,1)。錯誤發生在這一行:
img_gray[row 275][column 340] = face[row][column]
img_gray[row 275][column 340] 只需要一個值,因為 img_gray 具有 a 形狀(高度、寬度、1)。face[row][column] 的形狀為 (3,)
如果您執行以下操作,您會看到:
print(f"{ img_gray[row 275][column 340].shape} and {face[row][column].shape}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511471.html
