# 将图像二值化,黑色部分变为纯黑色 ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)修改为蓝色红色变为白色
时间: 2024-03-23 17:39:53 浏览: 128
可以使用以下代码将蓝色和红色变为白色,同时将图像二值化:
```python
import cv2
import numpy as np
img = cv2.imread('image.jpg')
# Convert BGR to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define range of blue and red color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
# Threshold the HSV image to get only blue and red colors
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask = mask_blue + mask_red
# Replace blue and red colors with white
img[mask>0] = (255,255,255)
# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Threshold the grayscale image to get binary image
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
# Show the binary image
cv2.imshow('Binary Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`lower_blue` 和 `upper_blue` 定义了蓝色的范围,`lower_red` 和 `upper_red` 定义了红色的范围。`mask_blue` 和 `mask_red` 分别是蓝色和红色的掩膜,通过 `+` 运算得到两个颜色的并集。然后将蓝色和红色对应的像素替换为白色。最后将图像转换为灰度图像,并进行二值化。
阅读全文