簡體   English   中英

如何去除圖片中的黑色背景?

[英]How do I remove the black background in the Image?

  • 下面的圖像分別包含黑色鰭狀肢上的豆子和石頭。

  • 我只想隔離下面腳蹼上的 object。 我使用cv2.inRange()但結果仍然很糟糕。

  • 我在下面寫了一個示例代碼:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

img_blured = cv2.blur(gray, (5, 5))
ret, thres = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY)

neg = cv2.bitwise_not(thres)
erosion = cv2.erode(neg, np.ones((6, 6), np.uint8), iterations=1)
cv2.imshow("erosion", erosion)

# ret, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
img[erosion == 0] = 0

圖 1

在此處輸入圖像描述

圖 2

在此處輸入圖像描述

期望的結果

在此處輸入圖像描述

hsv_image = cv2.cvtColor(img ,cv2.COLOR_BGR2HSV)
lower_orange_yellow = np.array([10, 50, 150])
upper_orange_yellow = np.array([35, 255, 255])
y_mask = cv2.inRange(hsv_image , lower_orange_yellow , upper_orange_yellow)
img[y_mask==0]=(0,0,0)

在此處輸入圖像描述

這是在 Python/OpenCV 中執行此操作的一種方法。

你的豆子顏色是黃色/橙色。

我注意到在 LAB 色彩空間中,“A 軸相對於綠-紅對手 colors,負值朝向綠色,正值朝向紅色。B 軸代表藍黃色對手,負數朝向藍色,正值朝向紅色。黃色。” https://en.wikipedia.org/wiki/CIELAB_color_space

所以想法是對LAB的B通道進行閾值化。

import cv2
import numpy as np

# read image
img1 = cv2.imread('bean1.jpg')
img2 = cv2.imread('bean2.jpg')

# convert to LAB and extract the B channel
B1 = cv2.cvtColor(img1, cv2.COLOR_BGR2LAB)[:,:,2]
B2 = cv2.cvtColor(img2, cv2.COLOR_BGR2LAB)[:,:,2]

# threshold on B channel
thresh1 = cv2.threshold(B1, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
thresh2 = cv2.threshold(B2, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# apply threshold as mask to image to blacken unwanted areas
result1 = img1.copy()
result1[thresh1==0] = (0,0,0)
result2 = img2.copy()
result2[thresh2==0] = (0,0,0)

# write results to disk
cv2.imwrite("bean1_extracted.png", result1)
cv2.imwrite("bean2_extracted.png", result2)

# display it
cv2.imshow("B1", B1)
cv2.imshow("B2", B2)
cv2.imshow("THRESH1", thresh1)
cv2.imshow("THRESH2", thresh2)
cv2.imshow("RESULT1", result1)
cv2.imshow("RESULT2", result2)
cv2.waitKey(0)

您需要定義一個 HSV 掩碼:

import cv2
import numpy as np

lower = np.array([6, 64, 0])
upper = np.array([23, 255, 255])

imgs = ["bean.jpg", "stone.jpg"]

for name in imgs:
    img = cv2.imread(name)
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(img_hsv, lower, upper)
    img_masked = cv2.bitwise_and(img, img, mask=mask)
    cv2.imshow(name, img_masked)

cv2.waitKey(0)

Output:

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

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

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