我想從放置所有內容的影像中選擇一個矩形框。換句話說,我想用不重要的(與內容無關的像素)像素洗掉影像的背景。輸出影像應該是一個矩形。
在 Python OpenCV 中執行此操作的最簡單方法是什么?(我將從檔案夾中匯入檔案......如果我可以自動化這個程序會更好)
uj5u.com熱心網友回復:
我希望你問的是“自動裁剪影像的空白”。這里我們假設一個二值影像:像素有高值和低值。
def focusToContent(img):
img_ = 255*(img < 128).astype(np.uint8)
coords = cv.findNonZero(img_) # Find all non-zero points (text)
x, y, w, h = cv.boundingRect(coords) # Find minimum spanning bounding box
rect = img[y:y h, x:x w] # Crop the image - note we do this on the original image
rect_originalSized = cv.resize(rect,(img.shape))
return rect_originalSized
img 應該是一個 opencv 影像(具有正確資料型別的 numpy 陣列)
測驗代碼
#testing
img = cv.imread(r"D:/ENTC/SEM_4/EN2550 - Fundamentals of Image Processing and Machine Vision/~images/int-rec/test/1650009171.5083215.png",0)
assert img is not None
focused = focusToContent(img)
fig,ax = plt.subplots(1,2)
ax[0].imshow(img,cmap="gray")
ax[1].imshow(focused,cmap="gray")
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514981.html
