技术python图片PILpython中的图片基础操作AllenTT2025-02-252025-05-08PIL (pillow)123import iofrom PIL import Imageimport matplotlib.pyplot as plt 基础读写123456789101112131415# 读取图片image = Image.open('/path/to/image.png').convert('RGB')image2 = Image.open(io.BytesIO(buffer)) # buffer is bytesimage3 = Image.open(requests.get(image_url, stream=True).raw)# 查看图像实例的属性print("""Format: {image.format}Size: {image.size} = (width, height)Mode: {image.mode} ∈ (L, RGB, RGBA, CMYK, YCbCr, HSV)""")# 保存图片image.save('/path/to/image.jpg', 'jpg') # 有损压缩存储image.save('/path/to/image.phg', 'png') # 无损存储 展示图片12345678910111213141516171819202122232425262728293031323334353637def show_one_image(image): if isinstance(image, str): image = Image.open(image).convert('RGB') plt.imshow(image); plt.axis('off'); plt.show()def show_images(image_files): if len(image_files) == 0: return # 定义每张图片的最大宽度和高度 max_width, max_height = 224, 224 # 打开并缩放图片 images = [] for img_file in image_files: img = Image.open(img_file) img = img.resize((max_width, max_height), Image.BILINEAR) images.append(img) # 计算拼接后的总宽度和高度 total_width = sum(img.width for img in images) max_height = max(img.height for img in images) # 创建新的空白图片 new_image = Image.new('RGB', (total_width, max_height)) # 拼接图片 x_offset = 0 for img in images: new_image.paste(img, (x_offset, 0)) x_offset += img.width # 在Jupyter Notebook中展示拼接后的图片 plt.imshow(new_image); plt.axis('off'); plt.show()def random_show_dir_images(dirname, k=5): from glob import glob import random fnames = glob(dirname.rstrip('/')+'/*.jpg') + glob(dirname.rstrip('/')+'/*.jpeg') + glob(dirname.rstrip('/')+'/*.png') show_images(random.choices(fnames, k=k)) resize12# 将图片强制缩放到224x224img = img.resize((224,224), Image.BILINEAR)