⑴ 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]