fig,ax = plt.subplots(2,2) ax[0,0].set_title('img_src') ax[0,0].imshow(cv2.cvtColor(img_src,cv2.COLOR_BGR2RGB))
时间: 2024-04-18 07:24:10 浏览: 8
这段代码使用了matplotlib库来创建一个2x2的子图,并将原始的图像(img_src)显示在左上角的子图中。cv2.cvtColor函数用于将BGR格式的图像转换为RGB格式,以便matplotlib能够正确地显示颜色。ax[0,0].set_title设置了子图的标题为'img_src',ax[0,0].imshow显示了转换后的图像。
相关问题
将以下代码增加保存图像功能: import matplotlib.pyplot as plt import numpy as np from skimage import io, filters, measure, color from skimage.filters import threshold_otsu from skimage import io, color, filters img = io.imread('leaf.jpg') gray_img = color.rgb2gray(img) thresh = filters.threshold_otsu(gray_img) binary = gray_img > thresh edges = filters.sobel(binary) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 3)) ax = axes.ravel() ax[0].imshow(img) ax[0].set_title("Original") ax[1].imshow(edges, cmap='gray') ax[1].set_title("Edges") for a in ax: a.axis('off') plt.tight_layout() plt.show()
以下是增加保存图像功能的代码:
```Python
import matplotlib.pyplot as plt
import numpy as np
from skimage import io, filters, measure, color
from skimage.filters import threshold_otsu
# 读取图像
img = io.imread('leaf.jpg')
gray_img = color.rgb2gray(img)
# 图像处理
thresh = filters.threshold_otsu(gray_img)
binary = gray_img > thresh
edges = filters.sobel(binary)
# 绘制图像
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 3))
ax = axes.ravel()
ax[0].imshow(img)
ax[0].set_title("Original")
ax[1].imshow(edges, cmap='gray')
ax[1].set_title("Edges")
for a in ax:
a.axis('off')
# 保存图像
plt.savefig('edges.png')
plt.tight_layout()
plt.show()
```
在代码的最后,我们使用 `plt.savefig()` 函数将绘制的图像保存为文件,文件名为 "edges.png"。这样,在程序运行结束后,我们就可以在当前工作目录中找到保存的图像文件了。
import matplotlib.pyplot as plt from PIL import Image # 读取图像 image = np.array(Image.open('0.jpg')) # 将图像数据归一化到 [0, 1] 范围内 image_norm = image.astype('float32') / 255.0 # 压缩图像 compressed_image = compress_image(image_norm, n_clusters=16) # 显示压缩前后的图像 fig, ax = plt.subplots(1, 2, figsize=(10, 5)) ax[0].imshow(image_norm) ax[0].set_title('Original Image') ax[1].imshow(compressed_image) ax[1].set_title('Compressed Image') plt.show()加上计算PSNR的代码
可以使用以下代码计算压缩后的图像与原始图像之间的 PSNR 值:
```
import numpy as np
import math
# 计算 PSNR
def psnr(img1, img2):
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return float('inf')
return 20 * math.log10(1.0 / math.sqrt(mse))
# 计算压缩前后图像的 PSNR
psnr_value = psnr(image_norm, compressed_image)
print("PSNR: {:.2f} dB".format(psnr_value))
```
这将在显示压缩前后的图像后,输出压缩前后图像的 PSNR 值。