numpy之通过数组与PIL.Image对象的互转进行图片处理

------------------------------------------------语法基础------------------------------------------------

import numpy                             相关模块

import PIL.Image                       相关模块

numpy.array(img)                       img对象转化为np数组

Image.fromarray(arr)                 np数组转化为img对象

------------------------------------------------代码实现------------------------------------------------

import numpy as np
import PIL.Image as I

# 新建图像,参数为图片模式,尺寸,初始颜色
img=I.new('RGB',(1000,1000),(255,255,255))
# 把此img对象转化为np对象
arr=np.array(img)


# 把选择的区域,转为指定的颜色,参数解释:
# arr:上面的那个arr
# color:你指定的颜色
# h1,h2:选择的区域的最高点和最低点
# x1,x2:选择的区域的最左边和最右边,这里缺省为0到-1
# space:自定义的区域,此区域生效,意味着前面的区域选择无效
def change_color(arr,color,h1=0,h2=-1,x1=0,x2=-1,space=np.array([])):
    if not space.any():
        space=arr[h1:h2,x1:x2]
    space[:,:,0]=color[0]
    space[:,:,1]=color[1]
    space[:,:,2]=color[2]
    return space


if __name__=='__main__':
    # 通过数组切割,并带入方法,我们得到这种线条和长方形
    # 因为np数组是视图切割,我们甚至不用接收返回值做后续处理
    change_color(arr,(255,0,0),100,101,100,-100)
    change_color(arr,(255,0,0),120,500,100,-100)
    change_color(arr,(0,255,0),520,800,100,-100)
    change_color(arr,(0,255,0),100,800,90,92)
    change_color(arr,(0,255,0),100,800,-90,-89)
    # 这里我们自定义了区域,得到了很多虚线
    space=arr[820:850:2,100:-100:3]
    change_color(arr,(0,0,0),space=space)
    # 操作完毕,我们把np数组转回img对象并显示
    img=I.fromarray(arr)
    img.show()

------------------------------------------------效果展示------------------------------------------------

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值