问题
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