【问题标题】:How can I remove especific color of this image?如何删除此图像的特定颜色?
【发布时间】:2022-01-02 07:09:39
【问题描述】:

我想删除图像Brain Image 的所有米色,从而得到其他图像(棕色、绿色、黄色和红色)。我尝试使用删除白色背景的相同代码来执行此操作,只修改了 RGB 代码,但没有奏效。 (如果在帖子中犯了一些错误,请见谅)

import cv2 
import numpy as np

# Read image
img = cv2.imread(r'D:\PY\mk1\mk1\sagitale1.png')
hh, ww = img.shape[:2]

# threshold on white
# Define lower and uppper limits
lower = np.array([101, 69, 51])
upper = np.array([255, 171, 142])

# Create mask to only select black
thresh = cv2.inRange(img, lower, upper)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(20,20))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# invert morp image
mask = 255 - thresh

# apply mask to image
result = cv2.bitwise_and(img, img, mask=mask)


# save results
cv2.imwrite('1_thresh.jpg', thresh)
cv2.imwrite('1_result.jpg', result)


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

【问题讨论】:

    标签: python numpy opencv


    【解决方案1】:

    您的颜色顺序相反。 OpenCV 按 B、G、R 顺序使用颜色。你需要稍微改变你的范围。你也不需要形态。

    所以以下对我来说适用于 Python/OpenCV。

    输入:

    import cv2 
    import numpy as np
    
    # Read image
    img = cv2.imread('brain.png')
    hh, ww = img.shape[:2]
    
    # threshold on white
    # Define lower and uppper limits
    lower = np.array([90, 120, 200])
    upper = np.array([170, 200, 255])
    
    # Create mask to only select black
    thresh = cv2.inRange(img, lower, upper)
    
    # invert threshold image
    mask = 255 - thresh
    
    # apply mask to image
    result = cv2.bitwise_and(img, img, mask=mask)
    
    # save results
    cv2.imwrite('1_thresh.jpg', thresh)
    cv2.imwrite('1_result.jpg', result)
    
    cv2.imshow('thresh', thresh)
    cv2.imshow('mask', mask)
    cv2.imshow('result', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    阈值图像:

    结果:

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多