写一段lbp直方图代码,要求能输出结果图片和直方图
时间: 2023-06-11 07:09:26 浏览: 68
下面是一个使用Python和OpenCV实现的LBP直方图代码示例:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
def get_lbp_histogram(image):
# Convert image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Calculate LBP image
radius = 1
n_points = 8 * radius
lbp = np.zeros_like(gray)
for i in range(radius, gray.shape[0]-radius):
for j in range(radius, gray.shape[1]-radius):
center = gray[i, j]
code = 0
for n in range(n_points):
x = i + int(radius * np.cos(2*np.pi*n/n_points))
y = j - int(radius * np.sin(2*np.pi*n/n_points))
if gray[x, y] > center:
code |= 1<<n
lbp[i, j] = code
# Calculate LBP histogram
hist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, 2**n_points+1), range=(0, 2**n_points))
hist = hist.astype("float")
hist /= (hist.sum() + 1e-7)
return hist, lbp
# Load image
image = cv2.imread("test.jpg")
# Calculate LBP histogram
hist, lbp = get_lbp_histogram(image)
# Plot LBP image and histogram
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(lbp, cmap="gray")
axs[0].set_title("LBP Image")
axs[1].bar(np.arange(len(hist)), hist)
axs[1].set_title("LBP Histogram")
plt.show()
# Save result image
cv2.imwrite("result.jpg", lbp)
```
在上面的代码中,`get_lbp_histogram()`函数接受一张图像,计算LBP直方图并返回结果。使用`cv2.imread()`函数加载测试图像(`test.jpg`),然后调用`get_lbp_histogram()`函数计算LBP直方图和LBP图像。最后,使用`matplotlib`库绘制LBP图像和直方图,并将结果保存到`result.jpg`文件中。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)