使用Python代码将上述特征图像合成一张大图,并以处理前的名字命名,保存下来并展示
时间: 2024-03-18 12:38:48 浏览: 59
可以使用以下代码将特征图像合成一张大图,并保存下来:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
def build_filters():
filters = []
ksize = 9
for theta in np.arange(0, np.pi, np.pi / 8):
for sigma in range(1, 6):
for frequency in (0.1, 0.2):
kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, frequency, 0.5, 0, ktype=cv2.CV_32F)
kernel /= 1.5 * kernel.sum()
filters.append(kernel)
return filters
def process(img, filters):
features = np.zeros((img.shape[0], img.shape[1], len(filters)), dtype=np.float32)
for i, kernel in enumerate(filters):
filtered = cv2.filter2D(img, cv2.CV_8UC3, kernel)
features[:, :, i] = filtered
return features
# 读取图像并转为灰度图
img = cv2.imread('lena.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 构建gabor滤波器组
filters = build_filters()
# 对图像进行gabor特征提取
features = process(gray, filters)
# 合成特征图像
merged_features = np.zeros((gray.shape[0]*5, gray.shape[1]*8))
for i in range(40):
row = i // 8
col = i % 8
merged_features[row*gray.shape[0]:(row+1)*gray.shape[0], col*gray.shape[1]:(col+1)*gray.shape[1]] = features[:, :, i]
# 保存合成图像
cv2.imwrite('lena_gabor.jpg', merged_features)
# 展示合成图像
plt.imshow(merged_features, cmap='gray')
plt.xticks([])
plt.yticks([])
plt.show()
```
这段代码将40个特征图像合成为一张大图,并保存为`lena_gabor.jpg`。展示出来的大图是一个$2560\times 1792$的矩阵,每个小方格的大小为$128\times 224$,其中第$i$个特征图像位于第$i//8$行、第$i\%8$列。
阅读全文