嘿,我以前也seen those points!
你的代碼做的是減少兩個圖像,im_dst
和im_src
的值,但此時你的im_src
褪色圖像只需移動到新的位置並顯示。相反,您應該將褪色和變形的圖像添加到目標圖像並輸出。下面是你的代碼的最後的修飾工作:
alpha = 0.5
im_dst = img1 * alpha
im_src = img2 * (1-alpha)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
im_blended = im_dst + im_out
cv2.imshow("Blended Warped Image", im_blended)
cv2.waitKey(0)
但是你只分爲img1
,而不是通過img2
255所以你要分割兩個第一。
但是,沒有理由手動執行此操作,因爲您必須擔心轉換圖像類型和縮放以及所有這些操作。相反,更簡單的方法是使用內置的OpenCV函數addWeighted()
將兩個圖像與alpha混合一起添加。所以,你的整個代碼反而會如此之短:
import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, im_out, beta, 0.0)
cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)
功能addWeighted()
乘以第一圖像im_dst
通過alpha
,並通過beta
第二圖像im_out
。最後一個參數是你可以在需要的時候增加結果的正面轉變。最後,結果是飽和的,這樣高於您的數據類型允許的最大值將被截斷。這樣,您的結果與您的輸入類型相同 - 您不必轉換爲浮點型。
最後一點關於您的代碼。很多教程,包括上面鏈接的,使用findHomography()
從四個匹配點獲得單應性。在這種情況下使用getPerspectiveTransform()
更合適。該功能findHomography()
發現基於許多匹配點的最佳單應,使用異常值拒絕方案,並隨機抽樣,以加快通過所有可能的四個一組的匹配點去。當然,它可以很好地適用於4個點的組合,但當您有四個匹配點時使用getPerspectiveTransform()
,如果您有四個以上匹配點,則使用findHomography()
更合理。雖然,令人煩惱的是,無論出於何種原因,您傳入getPerspectiveTransform()
的點必須是np.float32
。因此,這將是我對你的代碼的最終建議:
import cv2
import numpy as np
# Read source image.
im_src = cv2.imread('src.jpg')
# Four corners of the book in source image
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)
# Read destination image.
im_dst = cv2.imread('dst.jpg')
# Four corners of the book in destination image.
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)
# Calculate Homography
h = cv2.getPerspectiveTransform(pts_src, pts_dst)
# Warp source image to destination based on homography
warp_src = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
# Blend the warped image and the destination image
alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, warp_src, beta, 0.0)
# Show the output
cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)
這(和上面的所有其他解決方案)將產生以下圖片:
看起來像是[相關](https://開頭計算器.com/a/3375291/5997596) –
@AzatIbrakov我不想像Image.alpha_composite()或cv2.addWeighted()那樣簡單地疊加圖像。我也想匹配他們的同形異義詞! – Ank
這正是你想要的!你只是想使用'cv2.addWeighted()'或'。alpha_composite()'在帶目標圖像的變形圖像上。 –