OPPO R11 PlusPlus与OPPO R11 Plus对比?

python - PIL and numpy - Stack Overflow
Join the Stack Overflow Community
Stack Overflow is a community of 7.1 million programmers, just like you, helping each other.
J it only takes a minute:
Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's PixelAccess object would allow.
I've figured out how to place the pixel information in a useful 3D numpy array by way of:
pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)
But I can't seem to figure out how to load it back into the PIL object after I've done all my awesome transforms.
I'm aware of the putdata() method, but can't quite seem to get it to behave.
Any thoughts?
10.2k206274
You're not saying how exactly putdata() is not behaving. I'm assuming you're doing
&&& pic.putdata(a)
Traceback (most recent call last):
File "...blablabla.../PIL/Image.py", line 1185, in putdata
self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple
This is because putdata expects a sequence of tuples and you're giving it a numpy array. This
&&& data = list(tuple(pixel) for pixel in pix)
&&& pic.putdata(data)
will work but it is very slow.
As of PIL 1.1.6, the
&&& pix = numpy.array(pic)
although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).
Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).
43.2k20103128
Open I as an array:
&&& I = numpy.asarray(PIL.Image.open('test.jpg'))
Do some stuff to I, then, convert it back to an image:
&&& im = PIL.Image.fromarray(numpy.uint8(I))
If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on
in correlation.zip.
7,5251265116
You need to convert your image to a numpy array this way:
import numpy
import PIL
img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img)
3,352111734
The example, I have used today:
import PIL
import numpy
from PIL import Image
def resize_image(numpy_array_image, new_height):
# convert nympy array image to PIL.Image
image = Image.fromarray(numpy.uint8(numpy_array_image))
old_width = float(image.size[0])
old_height = float(image.size[1])
ratio = float( new_height / old_height)
new_width = int(old_width * ratio)
image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
# convert PIL.Image into nympy array back again
return array(image)
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
The week's top questions and answers
Important community announcements
Questions that need answers
By subscribing, you agree to the
rev .25821
Stack Overflow works best with JavaScript enabled13469人阅读
Numpy小记(14)
http://基本输入输出和文件输入输出文件名和文件对象本节介绍所举的例子都是传递的文件名,也可以传递已经打开的文件对象.例如对于load和save函数来说,如果使用文件对象的话,可以将多个数组储存到一个npy文件中:&&& a = np.arange(8)
&&& b = np.add.accumulate(a)
&&& c = a + b
&&& f = file(&result.npy&, &wb&)
&&& np.save(f, a) # 顺序将a,b,c保存进文件对象f
&&& np.save(f, b)
&&& np.save(f, c)
&&& f.close()
&&& f = file(&result.npy&, &rb&)
&&& np.load(f) # 顺序从文件对象f中读取内容
array([0, 1, 2, 3, 4, 5, 6, 7])
&&& np.load(f)
array([ 0,
6, 10, 15, 21, 28])
&&& np.load(f)
array([ 0,
9, 14, 20, 27, 35])
文件对象写入时的注意事项numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=’‘, footer=’‘, comments=’#‘)Save an array to a text file.np.savetxt(输出文件名,矩阵名)输出文件名应为二进制写入: doc_word_mat_file = open('./filename.txt', 'wb')
否则出错:&&& savetxt(doc_word_mat_file, doc_word_mat) ... &&& fh.write(asbytes(format % tuple(row) + newline))TypeError: must be str, not bytes所以推荐不要使用文件对象写入,用文件名写入numpy数组输出选项设置在屏幕上输出数组:print(mat1)Text formatting options([precision,&threshold,&...])Set printing options.()Return the current print options.(f[,&repr])Set a Python function to be used when pretty printing arrays.numpy数组打印效果设置多维数组强制打印全部输出如果一个数组用来打印太大了,NumPy自动省略中间部分而只打印角落。禁用NumPy的这种行为并强制打印整个数组,你可以设置printoptions参数来更改打印选项。np.set_printoptions(threshold=np.NaN)threshold : int, optional&& Total number of array elements which trigger summarizationrather than full repr (default 1000).使用set_printoptions设置输出精度np.set_printoptions(precision=3)
0.712]但是怎么没办法输出原本数据的最精确精度,如有的数据是10位小数,有的是8位,输出不好控制precision为多少好。精度过高就会出错。这时可以使用array.astype(str)转换成字符串输出。如[['40.475' '-74.08']& ['40.731508' '-74.3']]suppress消除小的数字使用科学记数法y=np.array([1.5e-10,1.5,1500])
1.500e+03]
np.set_printoptions(suppress=True)
1500. ]在本地应用打印选项 中, 你可以使用 contextmanager ...formatter参数允许你指定一个格式为每个类型的函数(注意结尾补0了)np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
0.712]奇怪的方式print(np.char.mod('%4.2f', eigen_value))
[][]numpy输出精度局部控制@contextmanager
def np_printoptions(*args, **kwargs):
numpy本地应用打印选项,如:
with np_printoptions(precision=3, suppress=True):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
np.set_printoptions(**original)
numpy文件存取NumPy提供了多种文件操作函数方便我们存取数组内容。文件存取的格式:二进制和文本。二进制格式的文件又分为NumPy专用的格式化二进制类型和无格式类型。Numpy binary files (NPY, NPZ)(file[,&mmap_mode,&allow_pickle,&...])Load arrays or pickled objects from .npy, .npz or pickled files.(file,&arr[,&allow_pickle,&fix_imports])Save an array to a binary file in NumPy .npy format.(file,&*args,&**kwds)Save several arrays into a single file in uncompressed .npz format.(file,&*args,&**kwds)Save several arrays into a single file in compressed .npz format.The format of these binary file types is documented innumpy.load和numpy.save函数(推荐在不需要查看保存数据的情况下使用)以NumPy专用的二进制类型保存数据,这两个函数会自动处理元素类型和shape等信息,使用它们读写数组就方便多了,但是numpy.save输出的文件很难和其它语言编写的程序读入:&&& np.save(&a.npy&, a)
&&& c = np.load( &a.npy& )
array([[ 0,
9, 10, 11]])
Note:1. 文件要保存为.npy文件类型,否则会出错2. 保存为numpy专用二进制格式后,就不能用notepad++打开(乱码)看了,这是相对tofile内建函数不好的一点numpy.savez函数如果你想将多个数组保存到一个文件中的话,可以使用numpy.savez函数。savez函数的第一个参数是文件名,其后的参数都是需要保存的数组,也可以使用关键字参数为数组起一个名字,非关键字参数传递的数组会自动起名为arr_0, arr_1, ...。savez函数输出的是一个压缩文件(扩展名为npz),其中每个文件都是一个save函数保存的npy文件,文件名对应于数组名。load函数自动识别npz文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容:&&& a = np.array([[1,2,3],[4,5,6]])
&&& b = np.arange(0, 1.0, 0.1)
&&& c = np.sin(b)
&&& np.savez(&result.npz&, a, b, sin_array = c)
&&& r = np.load(&result.npz&)
&&& r[&arr_0&] # 数组a
array([[1, 2, 3],
[4, 5, 6]])
&&& r[&arr_1&] # 数组b
array([ 0. ,
&&& r[&sin_array&] # 数组c
array([ 0.
如果你用解压软件打开result.npz文件的话,会发现其中有三个文件:arr_0.npy, arr_1.npy, sin_array.npy,其中分别保存着数组a, b, c的内容。numpy读取文本文件Text files(fname[,&dtype,&comments,&delimiter,&...])Load data from a text file.(fname,&X[,&fmt,&delimiter,&newline,&...])Save an array to a text file.(fname[,&dtype,&comments,&...])Load data from a text file, with missing values handled as specified.(file,&regexp,&dtype)Construct an array from a text file, using regular expression parsing.(string[,&dtype,&count,&sep])A new 1-D array initialized from raw binary or text data in a string.(fid[,&sep,&format])Write array to a file as text or binary (default).()Return the array as a (possibly nested) list.numpy.savetxt和numpy.loadtxt(推荐需要查看保存数据时使用)使用numpy.savetxt和numpy.loadtxt可以读写1维和2维的数组:np.loadtxt(FILENAME, dtype=int, delimiter=' ')numpy.loadtxt(fname, dtype=&type 'float'&, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)使用结构数组读入文件persontype = np.dtype({'names':['name', 'age', 'weight', 'height'],&&&&&&&&&&&&&&&&&&&&&& 'formats':['S32','i', 'f', 'f']})data = np.loadtxt(f, delimiter=&,&, dtype=persontype)np.savetxt(&a.txt&,a, fmt=&%d&,delimiter=&,&)&&& a = np.arange(0,12,0.5).reshape(4,-1)
&&& np.savetxt(&a.txt&, a) # 缺省按照'%.18e'格式保存数据,以空格分隔
&&& np.loadtxt(&a.txt&)
&&& np.savetxt(&a.txt&, a, fmt=&%d&, delimiter=&,&) #改为保存为整数,以逗号分隔
&&& np.loadtxt(&a.txt&,delimiter=&,&) # 读入的时候也需要指定逗号分隔
Note:savetxt缺省按照'%.18e'格式保存数据, 可以修改保存格式为‘%.8f'(小数点后保留8位的浮点数), ’%d'(整数)等等np.savetxt保存中文字符串数组实际上是不可以的,因为默认是wb格式保存,这样就是保存为bytes,py3中的str又是unicode,这样就算保存下来了,也并看不了保存下来的中文是什么。如:s = np.array([['工', '1'], ['q', '1']])
s = np.char.encode(s,'utf-8')
np.savetxt('/tmp/1.txt', s, fmt='%s')文件中只会这样显示:b'\xe5\xb7\xa5' b'1'b'q' b'1'所以有中文的话,而且实在想看文件中的内容,只有使用普通保存方法保存了:with open() as f: f.write(lines)什么的。[]loadtxt出错1 numpy.loadtxt读入的字符串总是bytes格式,总是在前面加了一个b原因:np.loadtxt and np.genfromtxt operate in byte mode, which is the default string type in Python 2. But Python 3 uses unicode, and marks bytestrings with this b.& numpy.loadtxt中也声明了:Note that generators should return byte strings for Python 3k.解决:使用numpy.loadtxt从文件读取字符串,最好使用这种方式np.loadtxt(filename, dtype=bytes).astype(str)[][]总结:载入txt文件:numpy.loadtxt()/numpy.savetxt()智能导入文本/csv文件:numpy.genfromtxt()/numpy.recfromcsv()高速,有效率但numpy特有的二进制格式:numpy.save()/numpy.load()2 ValueError: Wrong number of columns at line 78446 原因是数据问题,可能前面的数据都是3列而78446却是2或4列等等。查看数据nl data_test6.txt | grep -C 3 78446numpy.genfromtxtimport numpy as npnp.genfromtxt('filename', dtype= None)# array([(1, 2.0, 'buckle_my_shoe'), (3, 4.0, 'margery_door')], #& dtype=[('f0', '&i4'), ('f1', '&f8'), ('f2', '|S14')])Raw binary files(file[,&dtype,&count,&sep])Construct an array from data in a text or binary file.(fid[,&sep,&format])Write array to a file as text or binary (default).tofile和fromfile数组内建函数(not recommend)使用数组的方法函数tofile可以方便地将数组中数据以二进制的格式写进文件。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据:&&& a = np.arange(0,12)
&&& a.shape = 3,4
array([[ 0,
9, 10, 11]])
&&& a.tofile(&a.bin&)
&&& b = np.fromfile(&a.bin&, dtype=np.float) # 按照float类型读入数据
&&& b # 读入的数据是错误的
&&& a.dtype # 查看a的dtype
dtype('int32')
&&& b = np.fromfile(&a.bin&, dtype=np.int32) # 按照int32类型读入数据
&&& b # 数据是一维的
array([ 0,
9, 10, 11])
&&& b.shape = 3, 4 # 按照a的shape修改b的shape
array([[ 0,
9, 10, 11]])
Note:1. 读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。2. sep关键字参数:此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。{这样就可以通过notepad++打开查看, 不过数据是一行显示,不便于查看}user_item_mat.tofile(user_item_mat_filename, sep=' ')String formatting(a[,&max_line_width,&precision,&...])Return a string representation of an array.(arr[,&max_line_width,&precision,&...])Return the string representation of an array.(a[,&max_line_width,&precision,&...])Return a string representation of the data in an array.Memory mapping filesCreate a memory-map to an array stored in a binary file on disk.Base-n representations(num[,&width])Return the binary representation of the input number as a string.(number[,&base,&padding])Return a string representation of a number in the given base system.Data sources([destpath])A generic data source file (file, http, ftp, ...).from:ref: []
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1533882次
积分:18786
积分:18786
排名:第388名
原创:513篇
转载:73篇
评论:163条
文章:21篇
阅读:81225
阅读:21607
文章:13篇
阅读:43602
阅读:26270
文章:16篇
阅读:74515
文章:18篇
阅读:41395
Contact me1853人阅读
python(244)
shape为(3, 1)(表多维数组)与shape为(3, )(表一维数组)用法上有很大的不同
&&& x = np.random.randn(3)
array([ 0., -0., -0.6655509 ])
&&& x.shape
&&& y = np.random.randn(3, 1)
array([[ 0.],
&&& y.shape
不同之一:与list进行转换
&&& list(x)
[0.61253, -0.22431, -0.12798]
&&& list(y)
[array([ 0.]), array([ 1.]), array([-0.])]
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1145341次
积分:46561
积分:46561
排名:第62名
原创:3669篇
转载:35篇
评论:102条
文章:10篇
阅读:3332
阅读:4447
文章:15篇
阅读:19102
阅读:5199
文章:10篇
阅读:4793
文章:10篇
阅读:2853
(27)(120)(192)(72)(70)(88)(222)(271)(253)(266)(422)(341)(302)(260)(321)(133)(135)(105)(99)(26)(3)

我要回帖

更多关于 oppo r11 plus 的文章

 

随机推荐