简体   繁体   中英

How can I remove especific color of this image?

I want to remove all beige of the image Brain Image , resulting in the others (brown, green, yellow and red). I tried to do this with the same code I removed the white background, only modifying the RGB code, but didn't work. (sorry if a made some mistake on the post)

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()

You have your colors in the reverse order. OpenCV uses colors in B,G,R order. And you need to change your ranges a little. Also you do not need the morphology.

So the following works in Python/OpenCV for me.

Input:

在此处输入图像描述

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()

Threshold Image:

在此处输入图像描述

Result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM