我正在嘗試根據蒙版影像裁剪影像并將裁剪后的影像粘貼到新的背景影像上。我能夠做到這一點,但裁剪后的影像是灰色而不是原始影像中的顏色



從上圖中可以看出,裁剪后的影像顏色與原始源貓影像的顏色不同,裁剪后的影像是灰色的,而在原始影像中它包含金黃色。
我的代碼如下執行此操作
import cv2
src1=cv2.imread('cat.jpg',0)
mask=cv2.imread('mask_cat.jpg',0)
ret, thresh1 = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
src1 [thresh1==0] = 0
h, w = src1.shape
red = (0, 0, 0)
width, height = 1742, 815
back =cv2.cvtColor( create_blank(width, height, rgb_color=red),cv2.COLOR_BGR2GRAY)
hh, ww = back.shape
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
result = back.copy()
result[yoff:yoff h, xoff:xoff w] = src1
如何在裁剪后的影像中獲得與裁剪位置的原始源顏色相同的顏色?任何解決此問題的建議或幫助將不勝感激。
uj5u.com熱心網友回復:
import cv2
cat = cv2.imread('cat.jpg')
mask_cat = cv2.imread('mask_cat.jpg', 0)
result = cv2.bitwise_and(cat,cat,mask = mask_cat)

我還看到您嘗試重塑影像。可以按如下方式完成。
width, height = 1742, 815
reshaped_result = cv2.resize(result, dsize=(width, height))

將裁剪后的影像放置在調整大小的影像上
width, height = 1742, 815
result_final = np.zeros((height,width,3), np.uint8)
h, w = result.shape[:2]
hh, ww = result_final.shape[:2]
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
result_final[yoff:yoff h, xoff:xoff w] = result

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424378.html
標籤:Python python-3.x opencv 图像处理 计算机视觉
