gpt4 book ai didi

python - 在 OpenCV python 中将白色像素转换为黑色

转载 作者:太空宇宙 更新时间:2023-11-03 22:03:02 24 4
gpt4 key购买 nike

我正在尝试使用 python OpenCV 将输入图像的白色背景转换为黑色。但是所有白色像素都没有完全转换为黑色。我附上了输入和输出图像。

输入图像:

Input Image in the window

输出图像:

Output Image in the Window

我使用了以下代码进行转换:

img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0];

我该怎么办?

最佳答案

我知道这已经被回答了。我为您提供了一个编码的 Python 解决方案。

首先我找到了this thread解释如何去除白色像素。

结果:

result

另一个测试img:

编辑这是一种更好、更短的方法。在@ZdaR 评论循环图像矩阵后,我调查了它。

[更新代码]

img = cv2.imread("Images/test.pnt")

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

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

img[thresh == 255] = 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()

Source

[旧代码]

img = cv2.imread("Images/test.png")

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

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

white_px = np.asarray([255, 255, 255])
black_px = np.asarray([0, 0, 0])

(row, col) = thresh.shape
img_array = np.array(img)

for r in range(row):
for c in range(col):
px = thresh[r][c]
if all(px == white_px):
img_array[r][c] = black_px

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

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

使用的其他来源: OpenCV Morphological Transformations

关于python - 在 OpenCV python 中将白色像素转换为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com