Change the background color to black

空扰寡人 提交于 2021-01-01 08:13:41

问题


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


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/59268374/change-the-background-color-to-black

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!