我想将此背景更改为原始黑色。此背景不是纯黑色。它的值包含1、2或3。使用以下代码后,我得到的背景值非常接近黑色,但不是黑色。尽管背景看起来是黑色的
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()
答案 0 :(得分:0)
尝试替换此:
ret, thresh = cv2.threshold(gray, 0, 255, cv2. THRESH_BINARY)
img[thresh == 5] = 0
与此:
# threshold to 10% of the maximum
threshold = 0.10 * np.max(img)
img[gray <= threshold] = 0
问题是cv2.threshold()
不会为您计算阈值,而是应用一个阈值,例如,thresh
在您的代码中已经是阈值图像。
(已编辑)
答案 1 :(得分:0)
据我所知,这应该可以解决您的问题。
import cv2
gray = cv2.imread(r"brain.png", cv2.IMREAD_GRAYSCALE)
thresh_val = 5
gray[gray < thresh_val] = 0
除此之外,请注意
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
基本上将整个图像设置为255,因为第二个参数是阈值,并且每个高于阈值的像素都设置为第三个值255。