⑴ opencv python 调用resize函数时一直报错
你可以重新看一下opencv 的文档,重新理解一下resize函数。resize函数提供了两种方法来修改图像的大小,一种是提供一个目标图像大小(dsize)这和目标大小包含两个维度:width和heigth。换句话说就是我要告诉resize函数我要将图片变为dsize这么大/小。另一种方式是通过两个参数fx,fy,这两个参数是缩放比例,分别表示对目标图像的长宽进行缩放的比例。
⑵ Python怎么生成三维数
importnumpyasnp
a=np.array([1,2,3],dtype=int)#创建1*3维数组array([1,2,3])
type(a)#numpy.ndarray类型
a.shape#维数信息(3L,)
a.dtype.name#'int32'
a.size#元素个数:3
a.itemsize#每个元素所占用的字节数目:4
b=np.array([[1,2,3],[4,5,6]],dtype=int)#创建2*3维数组array([[1,2,3],[4,5,6]])
b.shape#维数信息(2L,3L)
b.size#元素个数:6
b.itemsize#每个元素所占用的字节数目:4
c=np.array([[1,2,3],[4,5,6]],dtype='int16')#创建2*3维数组array([[1,2,3],[4,5,6]],dtype=int16)
c.shape#维数信息(2L,3L)
c.size#元素个数:6
c.itemsize#每个元素所占用的字节数目:2
c.ndim#维数
d=np.array([[1,2,3],[4,5,6]],dtype=complex)#复数二维数组
d.itemsize#每个元素所占用的字节数目:16
d.dtype.name#元素类型:'complex128'
importnumpyasnp
a=np.array([1,2,3],dtype=int)#创建1*3维数组array([1,2,3])
type(a)#numpy.ndarray类型
a.shape#维数信息(3L,)
a.dtype.name#'int32'
a.size#元素个数:3
a.itemsize#每个元素所占用的字节数目:4
b=np.array([[1,2,3],[4,5,6]],dtype=int)#创建2*3维数组array([[1,2,3],[4,5,6]])
b.shape#维数信息(2L,3L)
b.size#元素个数:6
b.itemsize#每个元素所占用的字节数目:4
c=np.array([[1,2,3],[4,5,6]],dtype='int16')#创建2*3维数组array([[1,2,3],[4,5,6]],dtype=int16)
c.shape#维数信息(2L,3L)
c.size#元素个数:6
c.itemsize#每个元素所占用的字节数目:2
c.ndim#维数
d=np.array([[1,2,3],[4,5,6]],dtype=complex)#复数二维数组
d.itemsize#每个元素所占用的字节数目:16
d.dtype.name#元素类型:'complex128'
a1=np.zeros((3,4))#创建3*4全零二维数组
输出:
array([[0.,0.,0.,0.],
[0.,0.,0.,0.],
[0.,0.,0.,0.]])
a1.dtype.name#元素类型:'float64'
a1.size#元素个数:12
a1.itemsize#每个元素所占用的字节个数:8
a2=np.ones((2,3,4),dtype=np.int16)#创建2*3*4全1三维数组
a2=np.ones((2,3,4),dtype='int16')#创建2*3*4全1三维数组
输出:
array([[[1,1,1,1],
[1,1,1,1],
[1,1,1,1]],
[[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]],dtype=int16)
a3=np.empty((2,3))#创建2*3的未初始化二维数组
输出:(mayvary)
array([[1.,2.,3.],
[4.,5.,6.]])
a4=np.arange(10,30,5)#初始值10,结束值:30(不包含),步长:5
输出:array([10,15,20,25])
a5=np.arange(0,2,0.3)#初始值0,结束值:2(不包含),步长:0.2
输出:array([0.,0.3,0.6,0.9,1.2,1.5,1.8])
fromnumpyimportpi
np.linspace(0,2,9)#初始值0,结束值:2(包含),元素个数:9
输出:
array([0.,0.25,0.5,0.75,1.,1.25,1.5,1.75,2.])
x=np.linspace(0,2*pi,9)
输出:
array([0.,0.78539816,1.57079633,2.35619449,3.14159265,
3.92699082,4.71238898,5.49778714,6.28318531])
a=np.arange(6)
输出:
array([0,1,2,3,4,5])
b=np.arange(12).reshape(4,3)
输出:
array([[0,1,2],
[3,4,5],
[6,7,8],
[9,10,11]])
c=np.arange(24).reshape(2,3,4)
输出:
array([[[0,1,2,3],
[4,5,6,7],
[8,9,10,11]],
[[12,13,14,15],
[16,17,18,19],
[20,21,22,23]]])
使用numpy.set_printoptions可以设置numpy变量的打印格式
在ipython环境下,使用help(numpy.set_printoptions)查询使用帮助和示例
加法和减法操作要求操作双方的维数信息一致,均为M*N为数组方可正确执行操作。
a=np.arange(4)
输出:
array([0,1,2,3])
b=a**2
输出:
array([0,1,4,9])
c=10*np.sin(a)
输出:
array([0.,8.41470985,9.09297427,1.41120008])
n<35
输出:
array([True,True,True,True],dtype=bool)
A=np.array([[1,1],[0,1]])
B=np.array([[2,0],[3,4]])
C=A*B#元素点乘
输出:
array([[2,0],
[0,4]])
D=A.dot(B)#矩阵乘法
输出:
array([[5,4],
[3,4]])
E=np.dot(A,B)#矩阵乘法
输出:
array([[5,4],
[3,4]])
多维数组操作过程中的类型转换
When operating with arrays of different types, the type of the
resulting array corresponds to the more general or precise one (a
behavior known as upcasting)
即操作不同类型的多维数组时,结果自动转换为精度更高类型的数组,即upcasting
数组索引、切片和迭代
a=np.ones((2,3),dtype=int)#int32
b=np.random.random((2,3))#float64
b+=a#正确
a+=b#错误
a=np.ones(3,dtype=np.int32)
b=np.linspace(0,pi,3)
c=a+b
d=np.exp(c*1j)
输出:
array([0.54030231+0.84147098j,-0.84147098+0.54030231j,
-0.54030231-0.84147098j])
d.dtype.name
输出:
'complex128'
多维数组的一元操作,如求和、求最小值、最大值等
a=np.random.random((2,3))
a.sum()
a.min()
a.max()
b=np.arange(12).reshape(3,4)
输出:
array([[0,1,2,3],
[4,5,6,7],
[8,9,10,11]])
b.sum(axis=0)#按列求和
输出:
array([12,15,18,21])
b.sum(axis=1)#按行求和
输出:
array([6,22,38])
b.cumsum(axis=0)#按列进行元素累加
输出:
array([[0,1,2,3],
[4,6,8,10],
[12,15,18,21]])
b.cumsum(axis=1)#按行进行元素累加
输出:
array([[0,1,3,6],
[4,9,15,22],
[8,17,27,38]])
universal functions
B=np.arange(3)
np.exp(B)
np.sqrt(B)
C=np.array([2.,-1.,4.])
np.add(B,C)
其他的ufunc函数包括:
all,any,apply_along_axis,argmax,argmin,argsort,average,bincount,ceil,clip,conj,corrcoef,cov,cross,cumprod,cumsum,diff,dot,floor,inner,lexsort,max,maximum,mean,median,min,minimum,nonzero,outer,prod,re,round,sort,std,sum,trace,transpose,var,vdot,vectorize,where
a=np.arange(10)**3
a[2]
a[2:5]
a[::-1]#逆序输出
foriina:
print(i**(1/3.))
deff(x,y):
return10*x+y
b=np.fromfunction(f,(5,4),dtype=int)
b[2,3]
b[0:5,1]
b[:,1]
b[1:3,:]
b[-1]
c=np.array([[[0,1,2],[10,11,12]],[[100,101,102],[110,111,112]]])
输出:
array([[[0,1,2],
[10,11,12]],
[[100,101,102],
[110,111,112]]])
c.shape
输出:
(2L,2L,3L)
c[0,...]
c[0,:,:]
输出:
array([[0,1,2],
[10,11,12]])
c[:,:,2]
c[...,2]
输出:
array([[2,12],
[102,112]])
forrowinc:
print(row)
forelementinc.flat:
print(element)
a=np.floor(10*np.random.random((3,4)))
输出:
array([[3.,9.,8.,4.],
[2.,1.,4.,6.],
[0.,6.,0.,2.]])
a.ravel()
输出:
array([3.,9.,8.,...,6.,0.,2.])
a.reshape(6,2)
输出:
array([[3.,9.],
[8.,4.],
[2.,1.],
[4.,6.],
[0.,6.],
[0.,2.]])
a.T
输出:
array([[3.,2.,0.],
[9.,1.,6.],
[8.,4.,0.],
[4.,6.,2.]])
a.T.shape
输出:
(4L,3L)
a.resize((2,6))
输出:
array([[3.,9.,8.,4.,2.,1.],
[4.,6.,0.,6.,0.,2.]])
a.shape
输出:
(2L,6L)
a.reshape(3,-1)
输出:
array([[3.,9.,8.,4.],
[2.,1.,4.,6.],
[0.,6.,0.,2.]])
详查以下函数:
ndarray.shape,reshape,resize,ravel
a=np.floor(10*np.random.random((2,2)))
输出:
array([[5.,2.],
[6.,2.]])
b=np.floor(10*np.random.random((2,2)))
输出:
array([[0.,2.],
[4.,1.]])
np.vstack((a,b))
输出:
array([[5.,2.],
[6.,2.],
[0.,2.],
[4.,1.]])
np.hstack((a,b))
输出:
array([[5.,2.,0.,2.],
[6.,2.,4.,1.]])
fromnumpyimportnewaxis
np.column_stack((a,b))
输出:
array([[5.,2.,0.,2.],
[6.,2.,4.,1.]])
a=np.array([4.,2.])
b=np.array([2.,8.])
a[:,newaxis]
输出:
array([[4.],
[2.]])
b[:,newaxis]
输出:
array([[2.],
[8.]])
np.column_stack((a[:,newaxis],b[:,newaxis]))
输出:
array([[4.,2.],
[2.,8.]])
np.vstack((a[:,newaxis],b[:,newaxis]))
输出:
array([[4.],
[2.],
[2.],
[8.]])
np.r_[1:4,0,4]
输出:
array([1,2,3,0,4])
np.c_[np.array([[1,2,3]]),0,0,0,np.array([[4,5,6]])]
输出:
array([[1,2,3,0,0,0,4,5,6]])
详细使用请查询以下函数:
hstack,vstack,column_stack,concatenate,c_,r_
a=np.floor(10*np.random.random((2,12)))
输出:
array([[9.,7.,9.,...,3.,2.,4.],
[5.,3.,3.,...,9.,7.,7.]])
np.hsplit(a,3)
输出:
[array([[9.,7.,9.,6.],
[5.,3.,3.,1.]]),array([[7.,2.,1.,6.],
[7.,5.,0.,2.]]),array([[9.,3.,2.,4.],
[3.,9.,7.,7.]])]
np.hsplit(a,(3,4))
输出:
[array([[9.,7.,9.],
[5.,3.,3.]]),array([[6.],
[1.]]),array([[7.,2.,1.,...,3.,2.,4.],
[7.,5.,0.,...,9.,7.,7.]])]
实现类似功能的函数包括:
hsplit,vsplit,array_split
a=np.arange(12)
输出:
array([0,1,2,...,9,10,11])
notatall
b=a
bisa#True
b.shape=3,4
a.shape#(3L,4L)
deff(x)#,sofunctioncallsmakeno.
print(id(x))#id是python对象的唯一标识符
id(a)#111833936L
id(b)#111833936L
f(a)#111833936L
浅复制
c=a.view()
cisa#False
c.baseisa#True
c.flags.owndata#False
c.shape=2,6
a.shape#(3L,4L)
c[0,4]=1234
print(a)
输出:
array([[0,1,2,3],
[1234,5,6,7],
[8,9,10,11]])
s=a[:,1:3]
s[:]=10
print(a)
输出:
array([[0,10,10,3],
[1234,10,10,7],
[8,10,10,11]])
深复制
d=a.()
disa#False
d.baseisa#False
d[0,0]=9999
print(a)
输出:
array([[0,10,10,3],
[1234,10,10,7],
[8,10,10,11]])
numpy基本函数和方法一览
Array Creation
arange,array,,empty,empty_like,eye,fromfile,fromfunction,identity,linspace,logspace,mgrid,ogrid,ones,ones_like,r,zeros,zeros_like
Conversions
ndarray.astype,atleast_1d,atleast_2d,atleast_3d,mat
Manipulations
array_split,column_stack,concatenate,diagonal,dsplit,dstack,hsplit,hstack,ndarray.item,newaxis,ravel,repeat,reshape,resize,squeeze,swapaxes,take,transpose,vsplit,vstack
Questionsall,any,nonzero,where
Ordering
argmax,argmin,argsort,max,min,ptp,searchsorted,sort
Operations
choose,compress,cumprod,cumsum,inner,ndarray.fill,imag,prod,put,putmask,real,sum
Basic Statistics
cov,mean,std,var
Basic Linear Algebra
cross,dot,outer,linalg.svd,vdot
完整的函数和方法一览表链接:
https://docs.scipy.org/doc/numpy-dev/reference/routines.html#routines
⑶ python关于numpy基础问题
Python发展至今,已经有越来越多的人使用python进行科学技术,NumPY是python中的一款高性能科学计算和数据分析的基础包。
ndarray
ndarray(以下简称数组)是numpy的数组对象,需要注意的是,它是同构的,也就是说其中的所有元素必须是相同的类型。其中每个数组都有一个shape和dtype。
shape既是数组的形状,比如
复制代码
1 import numpy as np
2 from numpy.random import randn
3
4 arr = randn(12).reshape(3, 4)
5
6 arr
7
8 [[ 0.98655235 1.20830283 -0.72135183 0.40292924]
9 [-0.05059849 -0.02714873 -0.62775486 0.83222997]
10 [-0.84826071 -0.29484606 -0.76984902 0.09025059]]
11
12 arr.shape
13 (3, 4)
复制代码
其中(3, 4)即代表arr是3行4列的数组,其中dtype为float64
一下函数可以用来创建数组
array将输入数据转换为ndarray,类型可制定也可默认
asarray将输入转换为ndarray
arange类似内置range
ones、ones_like根据形状创建一个全1的数组、后者可以复制其他数组的形状
zeros、zeros_like类似上面,全0
empty、empty_like创建新数组、只分配空间
eye、identity创建对角线为1的对角矩阵
数组的转置和轴对称
转置是多维数组的基本运算之一。可以使用.T属性或者transpose()来实现。.T就是进行轴对换而transpose则可以接收参数进行更丰富的变换
复制代码
arr = np.arange(6).reshape((2,3))
print arr
[[0 1 2]
[3 4 5]]
print arr.T
[[0 3]
[1 4]
[2 5]]
arr = np.arange(24).reshape((2,3,4))
print arr
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
print arr.transpose((0,1,2))
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
复制代码
数组的运算
大小相等的数组之间做任何算术运算都会将运算应用到元素级别。
复制代码
1 arr = np.arange(9).reshape(3, 3)
2 print arr
3
4 [[0 1 2]
5 [3 4 5]
6 [6 7 8]]
7
8 print arr*arr
9
10 [[ 0 1 4]
11 [ 9 16 25]
12 [36 49 64]]
13
14 print arr+arr
15
16 [[ 0 2 4]
17 [ 6 8 10]
18 [12 14 16]]
19
20 print arr*4
21
22 [[ 0 4 8]
23 [12 16 20]
24 [24 28 32]]
复制代码
numpy的简单计算中,ufunc通用函数是对数组中的数据执行元素级运算的函数。
如:
复制代码
arr = np.arange(6).reshape((2,3))
print arr
[[0 1 2]
[3 4 5]]
print np.square(arr)
[[ 0 1 4]
[ 9 16 25]]
复制代码
类似的有:abs,fabs,sqrt,square,exp,log,sign,ceil,floor,rint,modf,isnan,isfinite,isinf,cos,cosh,sin,sinh,tan,tanh,
add,subtract,multiply,power,mod,equal,等等
⑷ python resize和reshape的区别
0. reshape的参数
reshape的参数严格地说,应该是tuple类型(tuple of ints),似乎不是tuple也成(ints)。
>>> x = np.random.rand(2, 3)
>>> x.reshape((3, 2))
# 以tuple of ints
array([[ 0.19399632, 0.33569667],
[ 0.36343308, 0.7068406 ],
[ 0.89809989, 0.7316493 ]])
>>> x.reshape(3, 2)
array([[ 0.19399632, 0.33569667],
[ 0.36343308, 0.7068406 ],
[ 0.89809989, 0.7316493 ]])
1. .reshape 实现维度的提升
(3, ) (3, 1):前者表示一维数组(无行和列的概念),后者则表示一个特殊的二维数组,也即是一个列向量;
>> x = np.ones(3)
>> x
array([ 1., 1., 1.])
>> x.reshape(3, 1)
array([[ 1.],
[ 1.],
[ 1.]])
>> x.reshape(1, 3)
array([[ 1., 1., 1.]])
2. .reshape 与 .resize
reshape:有返回值,所谓有返回值,即不对原始多维数组进行修改;
resize:无返回值,所谓有返回值,即会对原始多维数组进行修改;
>> X = np.random.randn(2, 3)
>> X
array([[ 1.23077478, -0.70550605, -0.37017735],
[-0.61543319, 1.1188644 , -1.05797142]])
>> X.reshape((3, 2))
array([[ 1.23077478, -0.70550605],
[-0.37017735, -0.61543319],
[ 1.1188644 , -1.05797142]])
>> X
array([[ 1.23077478, -0.70550605, -0.37017735],
[-0.61543319, 1.1188644 , -1.05797142]])
>> X.resize((3, 2))
>> X
array([[ 1.23077478, -0.70550605],
[-0.37017735, -0.61543319],
[ 1.1188644 , -1.05797142]])
⑸ python,numpy数组如何返回最大值数组
如果是list,有max(list)
也可以自己写排序算法,比如冒泡排序
a=[3,4,2,6,3]for i in range(0,len(a)): for j in range(i+1,len(a)): first=int(a[i]) second=int(a[j]) if first<second: a[i]=a[j] a[j]=firstprint a[0]
⑹ python中numpy矩阵重排列是按行还是按列
Numpy可以使用reshape()函数进行矩阵重排列,默认按行排列(C语言风格),通过修改order参数可以改为按列排列(Fortran风格)。参考例子:
In[1]:importnumpyasnp
In[2]:a=np.array([[1,2,3],[4,5,6]])
In[3]:printa
[[123]
[456]]
In[4]:b=a.reshape((3,2))#默认按行排列
In[5]:printb
[[12]
[34]
[56]]
In[6]:c=a.reshape((3,2),order='F')#改为Fortran风格的按列排列
In[7]:printc
[[15]
[43]
[26]]
⑺ python中的numpy数组同时变化问题
a=[1,2,3,4]
a[3]=5
最终a=[1,2,3,5]
⑻ py2exe python24 NumPy错误意思是问题,怎么解决
from distutils.core import setup
import py2exe
from distutils.filelist import findall
import os
import matplotlib
matplotlibdatadir = matplotlib.get_data_path()
matplotlibdata = findall(matplotlibdatadir)
matplotlibdata_files = []
for f in matplotlibdata:
dirname = os.path.join('matplotlibdata', f[len(matplotlibdatadir)+1:])
matplotlibdata_files.append((os.path.split(dirname)[0], [f]))
packages = ['matplotlib', 'pytz']
includes = []
excludes = []
dll_excludes = ['libgdk_pixbuf-2.0-0.dll',
'libgobject-2.0-0.dll',
'libgdk-win32-2.0-0.dll',
'wxmsw26uh_vc.dll']
opts = { 'py2exe': { 'packages' : packages,
'includes' : includes,
'excludes' : excludes,
'dll_excludes' : dll_excludes
}
}
setup ( console=['test.py'],
options = opts,
data_files = matplotlibdata_files
)
I compile the application by running >setup.py py2exe
At the end of compilation phase, it is written :
The following moles appear to be missing
['AppKit', 'FFT', 'Foundation', 'Image', 'LinearAlgebra', 'MA', 'MLab', 'Matrix', 'Numeric', 'PyObjCTools', 'P
yQt4', 'Pyrex', 'Pyrex.Compiler', 'RandomArray', '_curses', '_ssl', 'backends.draw_if_interactive', 'backends.
new_figure_manager', 'backends.pylab_setup', 'backends.show', 'cairo', 'cairo.gtk', 'fcompiler.FCompiler', 'fc
ompiler.show_fcompilers', 'fltk', 'gd', 'gobject', 'gtk', 'lib.add_newdoc', 'matplotlib.enthought.pyface.actio
n', 'mlab.amax', 'mlab.amin', 'numarray', 'numarray.convolve', 'numarray.fft', 'numarray.ieeespecial', 'numarr
ay.linear_algebra', 'numarray.linear_algebra.mlab', 'numarray.ma', 'numarray.numeric', 'numarray.random_array'
, 'numerix.ArrayType', 'numerix.Complex', 'numerix.Complex32', 'numerix.Complex64', 'numerix.Float', 'numerix.
Float32', 'numerix.Float64', 'numerix.Int', 'numerix.Int16', 'numerix.Int32', 'numerix.Int8', 'numerix.NewAxis
', 'numerix.UInt16', 'numerix.UInt32', 'numerix.UInt8', 'numerix.absolute', 'numerix.add', 'numerix.all', 'num
erix.allclose', 'numerix.alltrue', 'numerix.arange', 'numerix.arccos', 'numerix.arccosh', 'numerix.arcsin', 'n
umerix.arcsinh', 'numerix.arctan', 'numerix.arctan2', 'numerix.arctanh', 'numerix.argmax', 'numerix.argmin', '
numerix.argsort', 'numerix.around', 'numerix.array', 'numerix.arrayrange', 'numerix.asarray', 'numerix.asum',
'numerix.bitwise_and', 'numerix.bitwise_or', 'numerix.bitwise_xor', 'numerix.ceil', 'numerix.choose', 'numerix
.clip', 'numerix.compress', 'numerix.concatenate', 'numerix.conjugate', 'numerix.convolve', 'numerix.cos', 'nu
merix.cosh', 'numerix.cross_correlate', 'numerix.cumproct', 'numerix.cumsum', 'numerix.diagonal', 'numerix.d
ivide', 'numerix.dot', 'numerix.equal', 'numerix.exp', 'numerix.fabs', 'numerix.fft.fft', 'numerix.fft.inverse
_fft', 'numerix.floor', 'numerix.fmod', 'numerix.fromfunction', 'numerix.fromstring', 'numerix.greater', 'nume
rix.greater_equal', 'numerix.hypot', 'numerix.identity', 'numerix.indices', 'numerix.innerproct', 'numerix.i
scontiguous', 'numerix.less', 'numerix.less_equal', 'numerix.log', 'numerix.log10', 'numerix.logical_and', 'nu
merix.logical_not', 'numerix.logical_or', 'numerix.logical_xor', 'numerix.matrixmultiply', 'numerix.maximum',
'numerix.minimum', 'numerix.mlab.amax', 'numerix.mlab.amin', 'numerix.mlab.cov', 'numerix.mlab.diff', 'numerix
.mlab.hanning', 'numerix.mlab.rand', 'numerix.mlab.std', 'numerix.mlab.svd', 'numerix.multiply', 'numerix.nega
tive', 'numerix.newaxis', 'numerix.nonzero', 'numerix.not_equal', 'numerix.nx', 'numerix.ones', 'numerix.outer
proct', 'numerix.pi', 'numerix.power', 'numerix.proct', 'numerix.put', 'numerix.putmask', 'numerix.rank',
'numerix.ravel', 'numerix.repeat', 'numerix.reshape', 'numerix.resize', 'numerix.searchsorted', 'numerix.shape
', 'numerix.sin', 'numerix.sinh', 'numerix.size', 'numerix.sometrue', 'numerix.sort', 'numerix.sqrt', 'numerix
.subtract', 'numerix.swapaxes', 'numerix.take', 'numerix.tan', 'numerix.tanh', 'numerix.trace', 'numerix.trans
pose', 'numerix.typecode', 'numerix.typecodes', 'numerix.where', 'numerix.which', 'numerix.zeros', 'numpy.Comp
lex', 'numpy.Complex32', 'numpy.Complex64', 'numpy.Float', 'numpy.Float32', 'numpy.Float64', 'numpy.Infinity',
'numpy.Int', 'numpy.Int16', 'numpy.Int32', 'numpy.Int8', 'numpy.UInt16', 'numpy.UInt32', 'numpy.UInt8', 'nump
y.inf', 'numpy.infty', 'numpy.oldnumeric', 'objc', 'paint', 'pango', 'pre', 'pyemf', 'qt', 'setuptools', 'setu
ptools.command', 'setuptools.command.egg_info', 'trait_sheet', 'matplotlib.numerix.Float', 'matplotlib.numerix
.Float32', 'matplotlib.numerix.absolute', 'matplotlib.numerix.alltrue', 'matplotlib.numerix.asarray', 'matplot
lib.numerix.ceil', 'matplotlib.numerix.equal', 'matplotlib.numerix.fromstring', 'matplotlib.numerix.indices',
'matplotlib.numerix.put', 'matplotlib.numerix.ravel', 'matplotlib.numerix.sqrt', 'matplotlib.numerix.take', 'm
atplotlib.numerix.transpose', 'matplotlib.numerix.where', 'numpy.core.conjugate', 'numpy.core.equal', 'numpy.c
ore.less', 'numpy.core.less_equal', 'numpy.dft.old', 'numpy.random.rand', 'numpy.random.randn']
1) First Problem: numpy\core\_internal.pyc not included in Library.zip
No scipy-style subpackage 'core' found in C:\WinCE\Traces\py2exe test\dist\library.zip\numpy. Ignoring: No mole named _internal
Traceback (most recent call last):
File "profiler_ftt.py", line 15, in ?
from matplotlib.backends.backend_wx import Toolbar, FigureCanvasWx,\
File "matplotlib\backends\backend_wx.pyc", line 152, in ?
File "matplotlib\backend_bases.pyc", line 10, in ?
File "matplotlib\colors.pyc", line 33, in ?
File "matplotlib\numerix\__init__.pyc", line 67, in ?
File "numpy\__init__.pyc", line 35, in ?
File "numpy\_import_tools.pyc", line 173, in __call__
File "numpy\_import_tools.pyc", line 68, in _init_info_moles
File "<string>", line 1, in ?
File "numpy\lib\__init__.pyc", line 5, in ?
File "numpy\lib\type_check.pyc", line 8, in ?
File "numpy\core\__init__.pyc", line 6, in ?
File "numpy\core\umath.pyc", line 12, in ?
File "numpy\core\umath.pyc", line 10, in __load
AttributeError: 'mole' object has no attribute '_ARRAY_API'
I resolved that issue by adding the file ...\Python24\Lib\site-packages\numpy\core\_internal.pyc in ...\test\dist\library.zip\numpy\core.
Each time I compile that executable, I add the file by hand.
Does anybody know how to automatically add that file?
2) Second problem: I don't know how to resolve that issue:
Traceback (most recent call last):
File "profiler_ftt.py", line 15, in ?
from matplotlib.backends.backend_wx import Toolbar, FigureCanvasWx,\
File "matplotlib\backends\backend_wx.pyc", line 152, in ?
File "matplotlib\backend_bases.pyc", line 10, in ?
File "matplotlib\colors.pyc", line 33, in ?
File "matplotlib\numerix\__init__.pyc", line 67, in ?
File "numpy\__init__.pyc", line 35, in ?
File "numpy\_import_tools.pyc", line 173, in __call__
File "numpy\_import_tools.pyc", line 68, in _init_info_moles
File "<string>", line 1, in ?
File "numpy\random\__init__.pyc", line 3, in ?
File "numpy\random\mtrand.pyc", line 12, in ?
File "numpy\random\mtrand.pyc", line 10, in __load
File "numpy.pxi", line 32, in mtrand
AttributeError: 'mole' object has no attribute 'dtype'
I don't find the file numpy.pxi in my file tree nor in \test\dist\library.zip.
I browsed the web in the hope to find a solution but nothing.
It seems that this issue is well known but no solution provided in mailing lists.
⑼ python中PLE调整图片大小,等比例压缩文件,怎么写代码
How do I read image data from a URL in Python?
importosimportImagefileName='c:/py/jb51.jpg'fp=open(fileName,'rb')im=Image.open(fp)fp.close()x,y=im.sizeifx <300or y <300:os.remove(fileName)from PIL import Imageimport requestsimport numpy as npfrom StringIO import StringIOresponse = requests.get(url)img = np.array(Image.open(StringIO(response.content)))
from PIL import Imageimport urllib2
im = Image.open(urllib2.urlopen(url))
or if you userequests:
from PIL import Imageimport requests
im = Image.open(requests.get(url, stream=True).raw)
[python] view plain
[html] view plain
#coding:utf-8
'''
python图片处理
'''
importImageasimage
#等比例压缩图片
defresizeImg(**args):
args_key={'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg={}
forkeyinargs_key:
ifkeyinargs:
arg[key]=args[key]
im=image.open(arg['ori_img'])
ori_w,ori_h=im.size
widthRatio=heightRatio=None
ratio=1
if(ori_wandori_w>arg['dst_w'])or(ori_handori_h>arg['dst_h']):
ifarg['dst_w']andori_w>arg['dst_w']:
widthRatio=float(arg['dst_w'])/ori_w#正确获取小数的方式
ifarg['dst_h']andori_h>arg['dst_h']:
heightRatio=float(arg['dst_h'])/ori_h
ifwidthRatioandheightRatio:
ifwidthRatio<heightRatio:
ratio=widthRatio
else:
ratio=heightRatio
ifwidthRatioandnotheightRatio:
ratio=widthRatio
ifheightRatioandnotwidthRatio:
ratio=heightRatio
newWidth=int(ori_w*ratio)
newHeight=int(ori_h*ratio)
else:
newWidth=ori_w
newHeight=ori_h
im.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
'''
image.ANTIALIAS还有如下值:
NEAREST:usenearestneighbour
BILINEAR:
BICUBIC:
ANTIALIAS:bestdown-sizingfilter
'''
#裁剪压缩图片
defclipResizeImg(**args):
args_key={'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg={}
forkeyinargs_key:
ifkeyinargs:
arg[key]=args[key]
im=image.open(arg['ori_img'])
ori_w,ori_h=im.size
dst_scale=float(arg['dst_h'])/arg['dst_w']#目标高宽比
ori_scale=float(ori_h)/ori_w#原高宽比
ifori_scale>=dst_scale:
#过高
width=ori_w
height=int(width*dst_scale)
x=0
y=(ori_h-height)/3
else:
#过宽
height=ori_h
width=int(height*dst_scale)
x=(ori_w-width)/2
y=0
#裁剪
box=(x,y,width+x,height+y)
#这里的参数可以这么认为:从某图的(x,y)坐标开始截,截到(width+x,height+y)坐标
#所包围的图像,crop方法与php中的image方法大为不一样
newIm=im.crop(box)
im=None
#压缩
ratio=float(arg['dst_w'])/width
newWidth=int(width*ratio)
newHeight=int(height*ratio)
newIm.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
#水印(这里仅为图片水印)
defwaterMark(**args):
args_key={'ori_img':'','dst_img':'','mark_img':'','water_opt':''}
arg={}
forkeyinargs_key:
ifkeyinargs:
arg[key]=args[key]
im=image.open(arg['ori_img'])
ori_w,ori_h=im.size
mark_im=image.open(arg['mark_img'])
mark_w,mark_h=mark_im.size
option={'leftup':(0,0),'rightup':(ori_w-mark_w,0),'leftlow':(0,ori_h-mark_h),
'rightlow':(ori_w-mark_w,ori_h-mark_h)
}
im.paste(mark_im,option[arg['water_opt']],mark_im.convert('RGBA'))
im.save(arg['dst_img'])
#Demon
#源图片
ori_img='D:/tt.jpg'
#水印标
mark_img='D:/mark.png'
#水印位置(右下)
water_opt='rightlow'
#目标图片
dst_img='D:/python_2.jpg'
#目标图片大小
dst_w=94
dst_h=94
#保存的图片质量
save_q=35
#裁剪压缩
clipResizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q=save_q)
#等比例压缩
#resizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q=save_q)
#水印
#waterMark(ori_img=ori_img,dst_img=dst_img,mark_img=mark_img,water_opt=water_opt)
⑽ python使用numpy把向量扩展为矩阵
安装numpy,利用numpy数组: >>> import numpy >>> array1 = numpy.array([[1, 2], [3, 4]]) >>> array1 array([[1, 2], [3, 4]]) >>> array1 * 2.5 array([[ 2.5, 5. ], [ 7.5, 10. ]]) 如果你用的是python的列表,它的乘法是列表的自我复制,[1, 2] * 2就是[1, 2, 1, 2]