python生成灰度图

本文介绍如何使用Python中的PIL库加载图像,并将其转换为灰度显示。首先将图像文件读取为NumPy数组,如果图像有多个通道,则仅保留红色通道的数据。最后使用Matplotlib进行灰度图像展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

img = Image.open('lena.jpg')
img = np.array(img)
if img.ndim == 3:
    img = img[:,:,0]

plt.imshow(img, cmap = plt.cm.gray_r)
plt.show()
<think>我们使用Python生成灰度图有多种方法,这里将介绍两种常用方法:使用PIL库和matplotlib库。 1. 使用PIL(Pillow)库生成灰度图。 2. 使用matplotlib生成灰度图(例如灰度热力图)。 注意:灰度图通常只有一个通道,每个像素值在0(黑)到255(白)之间。 下面分别给出两种方法的代码示例。</think>### Python 生成灰度图的完整指南 #### 1. 使用 PIL/Pillow 库生成灰度图 ```python from PIL import Image, ImageDraw # 创建全新灰度图像 width, height = 400, 300 grayscale_img = Image.new('L', (width, height)) # 'L' 表示8位灰度 # 绘制渐变效果 draw = ImageDraw.Draw(grayscale_img) for y in range(height): for x in range(width): # 计算灰度值 (0-255) gray_value = int((x/width + y/height) * 128) draw.point((x, y), fill=gray_value) # 添加文字标注 draw.text((20, 20), "Python灰度图", fill=255) # 白色文字 # 保存图像 grayscale_img.save('gradient_grayscale.png') print("已生成渐变灰度图: gradient_grayscale.png") ``` #### 2. 使用 OpenCV 生成灰度图 ```python import cv2 import numpy as np # 创建空白灰度图像 gray_img = np.zeros((300, 400), dtype=np.uint8) # 添加圆形渐变 for y in range(300): for x in range(400): # 计算到中心点的距离 dist = np.sqrt((x-200)**2 + (y-150)**2) gray_img[y, x] = min(255, int(dist)) # 添加文字 cv2.putText(gray_img, 'OpenCV灰度图', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 255, 2) # 保存图像 cv2.imwrite('opencv_grayscale.png', gray_img) print("已生成OpenCV灰度图: opencv_grayscale.png") ``` #### 3. 使用 Matplotlib 生成灰度热力图 ```python import matplotlib.pyplot as plt import numpy as np # 生成数据 data = np.random.rand(10, 10) * 255 # 0-255的随机值 # 创建灰度图 fig, ax = plt.subplots(figsize=(8, 6)) im = ax.imshow(data, cmap='gray', vmin=0, vmax=255) # 添加颜色条 cbar = fig.colorbar(im, ax=ax) cbar.set_label('灰度值') # 添加标题和坐标 plt.title('Matplotlib灰度热力图') plt.xlabel('X轴') plt.ylabel('Y轴') # 保存为高分辨率灰度图 plt.savefig('matplotlib_grayscale.png', dpi=300, facecolor='none', bbox_inches='tight') plt.close() print("已生成Matplotlib灰度图: matplotlib_grayscale.png") ``` #### 4. 彩色图转灰度图的三种方法 ```python from PIL import Image import cv2 import numpy as np # 原始彩色图 color_img = Image.open('color_image.jpg') # 方法1: PIL转换 (Luminosity公式) grayscale_pil = color_img.convert('L') grayscale_pil.save('converted_pil.jpg') # 方法2: OpenCV转换 (加权平均法) color_cv = cv2.imread('color_image.jpg') grayscale_cv = cv2.cvtColor(color_cv, cv2.COLOR_BGR2GRAY) cv2.imwrite('converted_cv.jpg', grayscale_cv) # 方法3: NumPy手动转换 (自定义权重) color_np = np.array(color_img) # 使用ITU-R BT.709标准权重 grayscale_np = np.dot(color_np[..., :3], [0.2126, 0.7152, 0.0722]).astype(np.uint8) Image.fromarray(grayscale_np).save('converted_numpy.jpg') ``` #### 5. 高级灰度处理技巧 ```python from PIL import Image, ImageOps, ImageFilter # 读取灰度图 img = Image.open('grayscale.png').convert('L') # 直方图均衡化增强对比度 img_eq = ImageOps.equalize(img) # 添加高斯模糊 img_blur = img.filter(ImageFilter.GaussianBlur(radius=2)) # 边缘检测 img_edges = img.filter(ImageFilter.FIND_EDGES) # 保存处理结果 img_eq.save('equalized.png') img_blur.save('blurred.png') img_edges.save('edges.png') # 创建多图对比 comparison = Image.new('L', (img.width*3, img.height)) comparison.paste(img, (0, 0)) comparison.paste(img_eq, (img.width, 0)) comparison.paste(img_edges, (img.width*2, 0)) comparison.save('grayscale_comparison.png') ``` ### 灰度图生成最佳实践 1. **位深度选择**: - 8位灰度 (0-255):`'L'` 模式 - 16位灰度 (0-65535):使用 `np.uint16` 数组 2. **文件格式**: - PNG:无损压缩,适合图表 - JPEG:有损压缩,适合照片 - TIFF:支持16位深度 3. **元数据**: ```python from PIL import Image img = Image.open('grayscale.png') exif = img.getexif() exif[0x0112] = 1 # 设置方向标签 img.save('with_exif.png', exif=exif) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值