美文网首页Pythoner集中营生活不易 我用python
python | 图像抓取、加载与通道数处理

python | 图像抓取、加载与通道数处理

作者: 与阳光共进早餐 | 来源:发表于2018-07-20 15:17 被阅读20次

这篇文章整理了在处理大量图片数据集时可能需要用到的一些东西。

主要包括:

  • urllib根据图片url抓取图片并保存;
  • PILImage图像库加载图片;
  • crop函数对图像进行裁剪;
  • 处理数据集中的图像通道数,使其都为3通道;

1. 根据url下载图片

数据集很大的情况,常常需要我们自己去下载图片,这个时候就需要有个程序帮我们自动下载了。

  • 用urllib获取图片并保存
import urllib
# img_url: the url of image
# img_path: the path you want to save image
urllib.urlretrieve(img_url,img_path)

2. 图片加载与处理

1. 用PIL加载图像

from PIL import Image

def get_image_from_path(img_path,img_region):
    image = Image.open(img_path)
    image = process_image_channels(image, img_path)
    image = image.crop(img_region)
    return image

2. 关于crop函数

  • 一定要注意bounding_box的传入参数;
  • crop接受的参数为(左上x,左上y,右下x,右下y)
  • python的坐标系为最左上角为(0,0),横向x,纵向y;
  • 这里踩了好久的坑。╮(╯﹏╰)╭

3. 关于处理图像通道

  • 在这次处理的数据集中有jpg的图像,也有png的图像;
  • 以前从来不知道png会有RGBA4个通道甚至有些图片只有一个A通道,所以如果没有提前处理后面训练或者换测试的时候会时不时的给你一个bug小彩蛋哈哈哈。
  • 关键语句:
def process_image_channels(image, image_path):
    # process the 4 channels .png
    if image.mode == 'RGBA':
        r, g, b, a = image.split()
        image = Image.merge("RGB", (r, g, b))
    # process the 1 channel image
    elif image.mode != 'RGB':
        image = image.convert("RGB")
        os.remove(image_path)
        image.save(image_path)
    return image

简单的做个整理吧,后期有新的问题也会继续补充在这里。

相关文章

网友评论

    本文标题:python | 图像抓取、加载与通道数处理

    本文链接:https://www.haomeiwen.com/subject/viqqmftx.html