python

1 图片转灰度或者黑白

参考

from PIL import Image
col = Image.open("cat-tied-icon.png")
gray = col.convert('L')
gray.save(‘result_grey.png’)

bw = gray.point(lambda x: 0 if x<128 else 255, '1')
bw.save("result_bw.png")

2 PIL读取图片,更改尺寸

from PIL import Image
test = Image.open('4.jpg')
gray_image = test.convert('L') # 'L'表示灰度图像,'1'表示二值图像,
new_image = test.resize((28,28))

图形模式详情

resize是PIL是自带的更改尺寸函数,但会造成图片的变形

def letterbox_image(image, size):
    '''resize image with unchanged aspect ratio using padding'''
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)

    image = image.resize((nw,nh), Image.BICUBIC)
    #Image.new生成新的图片,彩色图片mode='RGB',灰色图片mode='L'
    new_image = Image.new('L', size, 128)
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image

3 读取图片,变更shape,相互转换

from PIL import Image
import numpy as np
test = Image.open('test.jpg')
atrr = np.array(test)
#atrr = atrr/255 #归一化

#变更shape有多种方式,如下
atrr_3d = np.expand_dims(atrr, axis=0)
#atrr_
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值