利用opencv编程实现直方图谷底法的图像二阈值分割。即绘制直方图,然后找到谷点设定为阈值T1和T2,使用这两个阈值将下面一副图像分成三种灰度级0,100,255。再将分割图进行伪彩色处理,背景颜色为紫色[140,50,250],房屋主体颜色为绿色[100,150,0],阴影颜色为蓝色[255,12,0]。
时间: 2024-02-22 08:58:33 浏览: 62
opencv实现灰度直方图,通过函数调用实现
5星 · 资源好评率100%
好的,我可以为您提供代码和解释。首先,需要导入以下库:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
```
然后读取原始图像并显示:
```python
img = cv2.imread('your_image_path', 0)
cv2.imshow('Original Image', img)
cv2.waitKey(0)
```
接下来,我们可以使用OpenCV的calcHist函数计算图像的直方图,然后绘制出来:
```python
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
plt.plot(hist)
plt.show()
```
接着,我们可以使用numpy库中的argmin函数找到直方图的谷点,即阈值T1和T2:
```python
valleys = np.gradient(np.squeeze(hist))
valleys = np.where(np.diff(np.sign(valleys)))[0] + 1
T1, T2 = valleys[0], valleys[-1]
```
然后,我们可以使用OpenCV的threshold函数将图像分成三个灰度级:
```python
ret, thresh1 = cv2.threshold(img, T1, 100, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, T2, 255, cv2.THRESH_BINARY_INV)
final_img = thresh2 + thresh1
```
最后,我们可以使用OpenCV的cvtColor函数将分割图进行伪彩色处理:
```python
colored_img = np.zeros((final_img.shape[0], final_img.shape[1], 3), dtype=np.uint8)
colored_img[np.where(final_img == 0)] = [140, 50, 250]
colored_img[np.where(final_img == 100)] = [100, 150, 0]
colored_img[np.where(final_img == 255)] = [255, 12, 0]
cv2.imshow('Colored Image', colored_img)
cv2.waitKey(0)
```
整个程序完整的代码如下:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
# read image
img = cv2.imread('your_image_path', 0)
cv2.imshow('Original Image', img)
cv2.waitKey(0)
# calculate histogram
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
plt.plot(hist)
plt.show()
# find valleys in histogram
valleys = np.gradient(np.squeeze(hist))
valleys = np.where(np.diff(np.sign(valleys)))[0] + 1
T1, T2 = valleys[0], valleys[-1]
# threshold image
ret, thresh1 = cv2.threshold(img, T1, 100, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, T2, 255, cv2.THRESH_BINARY_INV)
final_img = thresh2 + thresh1
# colorize image
colored_img = np.zeros((final_img.shape[0], final_img.shape[1], 3), dtype=np.uint8)
colored_img[np.where(final_img == 0)] = [140, 50, 250]
colored_img[np.where(final_img == 100)] = [100, 150, 0]
colored_img[np.where(final_img == 255)] = [255, 12, 0]
cv2.imshow('Colored Image', colored_img)
cv2.waitKey(0)
```
需要注意的是,在程序中要将"your_image_path"替换成您的图像路径。
阅读全文