1

I want to change this background into the original black. This background is not pure black. Its values contain 1, 2 or 3. After using the following code I got the background value very near to black but not black. Although the background looks black

img = cv2.imread("images.bmp")

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

ret, thresh = cv2.threshold(gray, 0, 255, cv2. THRESH_BINARY)

img[thresh == 5] = 0

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
erosion = cv2.erode(img, kernel, iterations = 1)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow("image", erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()

Input image

Georgy
  • 12,464
  • 7
  • 65
  • 73
tania
  • 67
  • 8
  • Related posts: [OpenCV Python - Set background colour](https://stackoverflow.com/q/29810128/7851470), [How to set background color on image to white with OpenCV in Python](https://stackoverflow.com/q/58465783/7851470). – Georgy Dec 10 '19 at 15:10

2 Answers2

0

Try replacing this:

ret, thresh = cv2.threshold(gray, 0, 255, cv2. THRESH_BINARY)

img[thresh == 5] = 0

with this:

# threshold to 10% of the maximum
threshold = 0.10 * np.max(img)
img[gray <= threshold] = 0

The issue is that cv2.threshold() does not compute a threshold for you, but applies one and, for example, thresh in your code is already the thresholded image.

(EDITED)

norok2
  • 25,683
  • 4
  • 73
  • 99
  • This will probably also set some dark pixels to black inside the area of interest, not only in the background. – Georgy Dec 10 '19 at 15:57
  • @Georgy Sure it will for some pixels, depending on the threshold value. – norok2 Dec 10 '19 at 17:04
  • @tania true, that in general. Is the case for your input as well? Your approach suffer the same problem. If you want a different way of describing your "background" beyond pixel values, you should, at the very least, provide in your question some insight of what you want to be considered "background". – norok2 Dec 12 '19 at 10:12
  • How do I select only background? – tania Dec 13 '19 at 01:42
0

This should fix your problem, to the best of my understanding.

import cv2

gray = cv2.imread(r"brain.png", cv2.IMREAD_GRAYSCALE)

thresh_val = 5
gray[gray < thresh_val] = 0

Besides that, watch out that

ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)

is basically going to set the whole image to 255, since the second argument is the threshold and every pixel above threshold is set to the third value, which is 255.

ndrplz
  • 1,584
  • 12
  • 16