簡體   English   中英

如何使用opencv丟棄圖像的邊緣?

[英]How to discard the edges of an image using opencv?

我正在預處理一些圖像,以便從我感興趣的區域中刪除背景。 但是,由於相機的焦點,我工作台上的圖像邊緣變圓。 如何丟棄這些圓角邊緣並僅從圖像中刪除我感興趣的對象? 下面的代碼我可以刪除圖像的背景,但由於周圍的邊緣而無法正常工作。

import numpy as np
import cv2

#Read the image and perform threshold and get its height and weight
img = cv2.imread('IMD408.bmp')
h, w = img.shape[:2]

# Transform to gray colorspace and blur the image.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)

# Make a fake rectangle arround the image that will seperate the main contour.
cv2.rectangle(blur, (0,0), (w,h), (255,255,255), 10)

# Perform Otsu threshold.
_,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# Create a mask for bitwise operation
mask = np.zeros((h, w), np.uint8)

# Search for contours and iterate over contours. Make threshold for size to
# eliminate others.
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

for i in contours:
    cnt = cv2.contourArea(i)
    if 1000000 >cnt > 100000:
        cv2.drawContours(mask, [i],-1, 255, -1)


# Perform the bitwise operation.
res = cv2.bitwise_and(img, img, mask=mask)

# Display the result.
cv2.imwrite('IMD408.png', res)
cv2.imshow('img', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

輸入圖像: 在此處輸入圖片說明

出口: 在此處輸入圖片說明

錯誤: 在此處輸入圖片說明

既然您提到所有圖像都具有相同的色調,那么這對它們來說應該很有效。 步驟是做一些白平衡,這將增加一點對比度。 在此處輸入圖片說明

獲取灰度。 在此處輸入圖片說明

閾值灰度圖像。 小於 127 的值設置為 255(白色)。 這將為您提供一個二值圖像,它將成為原始圖像的掩碼。

在此處輸入圖片說明 敷面膜

在此處輸入圖片說明

如果您想要更好的結果,您可能需要使用閾值,這是鏈接 但這應該讓你開始。 與您可能需要稍微調整代碼相比,我使用的是不同的 OpenCV 版本。

import cv2

def equaliseWhiteBalance(image):
    ''' Return equilised WB of an image '''
    wb = cv2.xphoto.createSimpleWB()                        #Create WB Object
    imgWB = wb.balanceWhite(img)                            #Balance White on image
    r,g,b = cv2.split(imgWB)                                #Get individual r,g,b channels
    r_equ  = cv2.equalizeHist(r)                            #Equalise RED channel
    g_equ  = cv2.equalizeHist(g)                            #Equalise GREEN channel
    b_equ  = cv2.equalizeHist(b)                            #Equalise BLUE channel
    img_equ_WB = cv2.merge([r_equ,g_equ,b_equ])             #Merge equalised channels
    return imgWB

#Read the image
img = cv2.imread('IMD408.bmp')
result = img.copy()

#Get whiteBalance of image
imgWB = equaliseWhiteBalance(img)

cv2.imshow('img', imgWB)
cv2.waitKey(0)

# Get gray image
gray = cv2.cvtColor(imgWB,cv2.COLOR_RGB2GRAY)
cv2.imshow('img', gray)
cv2.waitKey(0)

# Perform threshold
_, thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
cv2.imshow('img', thresh)
cv2.waitKey(0)

# Apply mask
result[thresh!=0] = (255,255,255)

cv2.imshow('img', result)
cv2.waitKey(0)

如果每個圖像的所有暗角小插圖都有不同的大小,那么我建議在二進制(蒙版)圖像上尋找輪廓的質心。 與圖像任何角落距離“短”的質心將是暗小插圖,因此它們的值可以從黑色更改為白色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM