c语言.jpg图片转成数组_Numpy 脑洞玩法之图片切割拼接

原标题:Numpy 脑洞玩法之图片切割拼接

来源:诡途

视频资料:

视频的内容介绍:一张照片,横着切成若干条,并且没有打乱,随后隔条分成了两份,然后把这两份各自拼接在一起,出现了跟两张原图一模一样的图片,将两张图竖着切成若干条,并且没有打乱,随后隔条分成了四份,出现了四张跟原图一模一样的图片(等比例缩小)

目标:使用Python实现图片切割拼接。

效果:效果如下图所示,证实这个实验是真的,只不过处理后的像素降低。

9bdadff4e78fccf236052c0b5793bbdd.png

原理:

Numpy对图像的处理实际上就是对ndarray的处理。图像和ndarray又有什么关系呢?图像是可以用ndarray数组来表示。如图我们可以用读取一张图片的数据,返回的就是这张图片的ndarray数组。通过对ndarray的处理实现图片操作

步骤解析:

【1】图片读取

读取一、PIL库的image

import numpy as np# pip install numpy import PIL.Image as img# pip install PIL data=np.array((''))

读取二、matplotlib库的pyplot

import numpy as np # pip install numpy import matplotlib.pyplot as plt # pip install matplotlib data=('')

ece26a3fa2bf1e257c60ccc04f944d09.png

# 查看数组的形状 data.shape # (800,800,3), # 第一个800代表图片的像素宽度-纵轴像素, # 第二个800代表图片的像素长度-横轴像素, #3代表RGB通道数,(有些图片格式是3通道,有些图片格式是4通道)

【2】图片切割 & 数组拼接

#图像切割——横轴切 width=[1] width0= (data,range(10,width,10),axis=1) width1=width0[::2] width2=width0[1::2] #数组的拼接——1轴|纵轴 test1 = (width1,axis=1) test2 = (width2,axis=1) print() (test1)

98f6b928fc7bb8cd39a598a96c77d7d8.png

#对切割后的test1再进行纵轴切割 length=[0] length0= (test1,range(10,length,10),axis=0) #test1 test2的length和原图等长 length1=length0[::2] length2=length0[1::2] #数组的拼接——0轴|横轴 test3 = (length1,axis=0) test4 = (length2,axis=0) print() (test3)

f5dba8119d53164bed50bf6f17192b82.png

【3】图片保存

保存一、scipy.misc

importscipy.misc scipy.misc.imsave( '',test3)

保存二、PIL库的image

#image img.fromarray( test3) .save(" test3.jpg")

保存三、matplotlib库的pyplot

plt.imsave(" test3.jpg", test3)

【4】完整代码:返回搜狐,查看更多

importnumpy as np # pip install numpy importmatplotlib.pyplot as plt # pip install matplotlib jpg_path= '' #n为切割的大小,n越大,像素越小 defcut_jpg(jpg_path,n): # 读取图片 data= (jpg_path) #图像切割_横轴切 width= [1] width0= (data,range(n,width+1,n),axis=1)#左闭右开所以+1 width1= width0[::2] width2= width0[1::2] #数组的拼接 test1= (width1,axis=1) test2= (width2,axis=1) #图像切割_纵轴切 length= [0] #test1 test2的length和原图等长,可以尝试同时切割 length0= (test1,range(n,length+1,n),axis=0)#左闭右开所以+1 length1= length0[::2] length2= length0[1::2] #数组的拼接 test3= (length1,axis=0) test4= (length2,axis=0) returntest3 #返回处理后的数组对象,test1,test2,test3,test4都是一样的,此处返回一组即可 test3= cut_jpg(jpg_path,5) #保存图片 ("",test3)

责任编辑:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值