pythonzeros
① 如何用 python 實現一個摳圖功能
要製作這樣的組合圖其實很簡單,最主要用到的就是美圖秀秀獨家新增的「添加前景」按鈕。當然,組合之前需要多摳取幾張圖片備用。
每摳好一張圖片後單擊「完成摳圖」,軟體就會將摳圖保存了。
② Python小問題
出現這個問題是因為索引出現了浮點數,不是索引允許的數據類型,可以驗證一下
importnumpyasnp
y=np.zeros(shape=(1,5))
arr=[nforninnp.linspace(1,5,5)]
arr里存儲的就是源代碼中會用的索引,下圖是結果
importnumpyasnp
y=np.zeros(shape=(1,5))
forninnp.int16(np.linspace(1,5,5)):
y[0,n-1]=n**2
print(y)
③ 想用python處理比較大的單色圖片文件,如何提高速度
你好,你可以考慮使用numpy的函數來做,下面是例子的python代碼
image=np.zeros((400,400,3),dtype="uint8")
raw=image.()
image[np.where((image==[0,0,0]).all(axis=2))]=[255,255,255]
cv2.imshow('Test0',image)
lower_black=np.array([0,0,0],dtype="uint16")
upper_black=np.array([70,70,70],dtype="uint16")
black_mask=cv2.inRange(image,lower_black,upper_black)
image[np.where((image==[0,0,0]).all(axis=2))]=[155,255,155]
black_mask[np.where(black_mask==[0])]=[155]
你把上面的那個image的數值改成你需要改的目標就可以直接替換了。
④ python np.zeros ValueError: array is too big.
這個庫我沒用過,不過一般產生這個問題,可能因為是array內部有限制,兩種方法:
一種是找到代碼中限制的地方,看看如果去掉的話會不會有問題。
另一種就是把這個array分成多個array進行操作。
如果解決了您的問題請採納!
如果未解決請繼續追問
⑤ 怎樣用python構建一個卷積神經網路模型
上周末利用python簡單實現了一個卷積神經網路,只包含一個卷積層和一個maxpooling層,pooling層後面的多層神經網路採用了softmax形式的輸出。實驗輸入仍然採用MNIST圖像使用10個feature map時,卷積和pooling的結果分別如下所示。
部分源碼如下:
[python]view plain
#coding=utf-8
'''''
Createdon2014年11月30日
@author:Wangliaofan
'''
importnumpy
importstruct
importmatplotlib.pyplotasplt
importmath
importrandom
import
#test
defsigmoid(inX):
if1.0+numpy.exp(-inX)==0.0:
return999999999.999999999
return1.0/(1.0+numpy.exp(-inX))
defdifsigmoid(inX):
returnsigmoid(inX)*(1.0-sigmoid(inX))
deftangenth(inX):
return(1.0*math.exp(inX)-1.0*math.exp(-inX))/(1.0*math.exp(inX)+1.0*math.exp(-inX))
defcnn_conv(in_image,filter_map,B,type_func='sigmoid'):
#in_image[num,featuremap,row,col]=>in_image[Irow,Icol]
#featuresmap[kfilter,row,col]
#type_func['sigmoid','tangenth']
#out_feature[kfilter,Irow-row+1,Icol-col+1]
shape_image=numpy.shape(in_image)#[row,col]
#print"shape_image",shape_image
shape_filter=numpy.shape(filter_map)#[kfilter,row,col]
ifshape_filter[1]>shape_image[0]orshape_filter[2]>shape_image[1]:
raiseException
shape_out=(shape_filter[0],shape_image[0]-shape_filter[1]+1,shape_image[1]-shape_filter[2]+1)
out_feature=numpy.zeros(shape_out)
k,m,n=numpy.shape(out_feature)
fork_idxinrange(0,k):
#rotate180tocalculateconv
c_filter=numpy.rot90(filter_map[k_idx,:,:],2)
forr_idxinrange(0,m):
forc_idxinrange(0,n):
#conv_temp=numpy.zeros((shape_filter[1],shape_filter[2]))
conv_temp=numpy.dot(in_image[r_idx:r_idx+shape_filter[1],c_idx:c_idx+shape_filter[2]],c_filter)
sum_temp=numpy.sum(conv_temp)
iftype_func=='sigmoid':
out_feature[k_idx,r_idx,c_idx]=sigmoid(sum_temp+B[k_idx])
eliftype_func=='tangenth':
out_feature[k_idx,r_idx,c_idx]=tangenth(sum_temp+B[k_idx])
else:
raiseException
returnout_feature
defcnn_maxpooling(out_feature,pooling_size=2,type_pooling="max"):
k,row,col=numpy.shape(out_feature)
max_index_Matirx=numpy.zeros((k,row,col))
out_row=int(numpy.floor(row/pooling_size))
out_col=int(numpy.floor(col/pooling_size))
out_pooling=numpy.zeros((k,out_row,out_col))
fork_idxinrange(0,k):
forr_idxinrange(0,out_row):
forc_idxinrange(0,out_col):
temp_matrix=out_feature[k_idx,pooling_size*r_idx:pooling_size*r_idx+pooling_size,pooling_size*c_idx:pooling_size*c_idx+pooling_size]
out_pooling[k_idx,r_idx,c_idx]=numpy.amax(temp_matrix)
max_index=numpy.argmax(temp_matrix)
#printmax_index
#printmax_index/pooling_size,max_index%pooling_size
max_index_Matirx[k_idx,pooling_size*r_idx+max_index/pooling_size,pooling_size*c_idx+max_index%pooling_size]=1
returnout_pooling,max_index_Matirx
defpoolwithfunc(in_pooling,W,B,type_func='sigmoid'):
k,row,col=numpy.shape(in_pooling)
out_pooling=numpy.zeros((k,row,col))
fork_idxinrange(0,k):
forr_idxinrange(0,row):
forc_idxinrange(0,col):
out_pooling[k_idx,r_idx,c_idx]=sigmoid(W[k_idx]*in_pooling[k_idx,r_idx,c_idx]+B[k_idx])
returnout_pooling
#out_featureistheoutputofconv
defbackErrorfromPoolToConv(theta,max_index_Matirx,out_feature,pooling_size=2):
k1,row,col=numpy.shape(out_feature)
error_conv=numpy.zeros((k1,row,col))
k2,theta_row,theta_col=numpy.shape(theta)
ifk1!=k2:
raiseException
foridx_kinrange(0,k1):
foridx_rowinrange(0,row):
foridx_colinrange(0,col):
error_conv[idx_k,idx_row,idx_col]=
max_index_Matirx[idx_k,idx_row,idx_col]*
float(theta[idx_k,idx_row/pooling_size,idx_col/pooling_size])*
difsigmoid(out_feature[idx_k,idx_row,idx_col])
returnerror_conv
defbackErrorfromConvToInput(theta,inputImage):
k1,row,col=numpy.shape(theta)
#print"theta",k1,row,col
i_row,i_col=numpy.shape(inputImage)
ifrow>i_roworcol>i_col:
raiseException
filter_row=i_row-row+1
filter_col=i_col-col+1
detaW=numpy.zeros((k1,filter_row,filter_col))
#thesamewithconvvalidinmatlab
fork_idxinrange(0,k1):
foridx_rowinrange(0,filter_row):
foridx_colinrange(0,filter_col):
subInputMatrix=inputImage[idx_row:idx_row+row,idx_col:idx_col+col]
#print"subInputMatrix",numpy.shape(subInputMatrix)
#rotatetheta180
#printnumpy.shape(theta)
theta_rotate=numpy.rot90(theta[k_idx,:,:],2)
#print"theta_rotate",theta_rotate
dotMatrix=numpy.dot(subInputMatrix,theta_rotate)
detaW[k_idx,idx_row,idx_col]=numpy.sum(dotMatrix)
detaB=numpy.zeros((k1,1))
fork_idxinrange(0,k1):
detaB[k_idx]=numpy.sum(theta[k_idx,:,:])
returndetaW,detaB
defloadMNISTimage(absFilePathandName,datanum=60000):
images=open(absFilePathandName,'rb')
buf=images.read()
index=0
magic,numImages,numRows,numColumns=struct.unpack_from('>IIII',buf,index)
printmagic,numImages,numRows,numColumns
index+=struct.calcsize('>IIII')
ifmagic!=2051:
raiseException
datasize=int(784*datanum)
datablock=">"+str(datasize)+"B"
#nextmatrix=struct.unpack_from('>47040000B',buf,index)
nextmatrix=struct.unpack_from(datablock,buf,index)
nextmatrix=numpy.array(nextmatrix)/255.0
#nextmatrix=nextmatrix.reshape(numImages,numRows,numColumns)
#nextmatrix=nextmatrix.reshape(datanum,1,numRows*numColumns)
nextmatrix=nextmatrix.reshape(datanum,1,numRows,numColumns)
returnnextmatrix,numImages
defloadMNISTlabels(absFilePathandName,datanum=60000):
labels=open(absFilePathandName,'rb')
buf=labels.read()
index=0
magic,numLabels=struct.unpack_from('>II',buf,index)
printmagic,numLabels
index+=struct.calcsize('>II')
ifmagic!=2049:
raiseException
datablock=">"+str(datanum)+"B"
#nextmatrix=struct.unpack_from('>60000B',buf,index)
nextmatrix=struct.unpack_from(datablock,buf,index)
nextmatrix=numpy.array(nextmatrix)
returnnextmatrix,numLabels
defsimpleCNN(numofFilter,filter_size,pooling_size=2,maxIter=1000,imageNum=500):
decayRate=0.01
MNISTimage,num1=loadMNISTimage("F:\train-images-idx3-ubyte",imageNum)
printnum1
row,col=numpy.shape(MNISTimage[0,0,:,:])
out_Di=numofFilter*((row-filter_size+1)/pooling_size)*((col-filter_size+1)/pooling_size)
MLP=BMNN2.MuiltilayerANN(1,[128],out_Di,10,maxIter)
MLP.setTrainDataNum(imageNum)
MLP.loadtrainlabel("F:\train-labels-idx1-ubyte")
MLP.initialweights()
#MLP.printWeightMatrix()
rng=numpy.random.RandomState(23455)
W_shp=(numofFilter,filter_size,filter_size)
W_bound=numpy.sqrt(numofFilter*filter_size*filter_size)
W_k=rng.uniform(low=-1.0/W_bound,high=1.0/W_bound,size=W_shp)
B_shp=(numofFilter,)
B=numpy.asarray(rng.uniform(low=-.5,high=.5,size=B_shp))
cIter=0
whilecIter<maxIter:
cIter+=1
ImageNum=random.randint(0,imageNum-1)
conv_out_map=cnn_conv(MNISTimage[ImageNum,0,:,:],W_k,B,"sigmoid")
out_pooling,max_index_Matrix=cnn_maxpooling(conv_out_map,2,"max")
pool_shape=numpy.shape(out_pooling)
MLP_input=out_pooling.reshape(1,1,out_Di)
#printnumpy.shape(MLP_input)
DetaW,DetaB,temperror=MLP.backwardPropogation(MLP_input,ImageNum)
ifcIter%50==0:
printcIter,"Temperror:",temperror
#printnumpy.shape(MLP.Theta[MLP.Nl-2])
#printnumpy.shape(MLP.Ztemp[0])
#printnumpy.shape(MLP.weightMatrix[0])
theta_pool=MLP.Theta[MLP.Nl-2]*MLP.weightMatrix[0].transpose()
#printnumpy.shape(theta_pool)
#print"theta_pool",theta_pool
temp=numpy.zeros((1,1,out_Di))
temp[0,:,:]=theta_pool
back_theta_pool=temp.reshape(pool_shape)
#print"back_theta_pool",numpy.shape(back_theta_pool)
#print"back_theta_pool",back_theta_pool
error_conv=backErrorfromPoolToConv(back_theta_pool,max_index_Matrix,conv_out_map,2)
#print"error_conv",numpy.shape(error_conv)
#printerror_conv
conv_DetaW,conv_DetaB=backErrorfromConvToInput(error_conv,MNISTimage[ImageNum,0,:,:])
#print"W_k",W_k
#print"conv_DetaW",conv_DetaW
⑥ python中如何生成一個全是0和1的矩陣
溢出測試時,常常需要生成一長串字元串去填充緩沖區,用循環的話比較麻煩。python中直接可以用乘號來操作字元串:
shellcode = 'x90' * 1000
執行後,shellcode的值為1000個x90。
同時也可以用加號來操作字元串,連接兩個字元串的例子如下:
import struct
buffer = 'A' * 100
jmpesp = struct('<L', 0x7ffa4512) #將0x7ffa4512轉化為x12x45xfax7f的格式
buffer += jmpesp
⑦ python中向量指的是什麼意思
一、向量是什麼
在數學中,向量(也稱為歐幾里得向量、幾何向量、矢量),指具有大小(magnitude)和方向的量。它可以形象化地表示為帶箭頭的線段。箭頭所指:代表向量的方向;線段長度:代表向量的大小。與向量對應的只有大小,沒有方向的量叫做數量(物理學中稱標量)
在這里,向量即一維數組,用 arange 函數創建向量是最簡單的方式之一:
arange函數也可以指定初始值、終止值和步長來創建一維數組:
向量還能直接對每個元素進行運算:
二、創建向量
上面使用 arange 則是創建向量的一種方式,其實只要是數組創建的函數均可以創建向量,如:
linspace() 函數
前文介紹:linspace 通過制定初始值、終止值和元素個數創建等差數列向量,通過endpoint 參數指定是否包含終止值,默認為True
logspace() 函數
同linspace,創建等比數列,基數通過base參數指定,默認基數為10
zeros() 函數和 ones() 函數
這兩個函數分別可以創建指定長度或形狀的全0或全1的 ndarray 數組,比如:
指定數據類型:
empty() 函數
這個函數可以創建一個沒有任何具體值的 ndarray 數組,例如:
random.randn() 函數
randn 是 numpy.random 中生成正態分布隨機數據的函數
fromstring() 函數
從字元串創建數組
上面從字元串創建的數組,定義為整形8bit,創建出來的其實就是字元串的ASCII 碼
fromfunction() 函數
從函數創建數組,是數據分析常見的方法
可先定義一個從下標計算數值的函數,然後用fromfunction 創建數組
fromfunction 第一個參數為計算每個數組元素的函數名,第二個參數指定數組的形狀。因為它支持多維數組,所以第二個參數必須是一個序列。
例如我創建一個九九乘法表:
注意,fromfunction 函數中的第二個參數指定的是數組的下標,下標作為實參通過遍歷的方式傳遞給函數的形參。
眾多python培訓視頻,盡在python學習網,歡迎在線學習!
⑧ python 怎麼遍歷numpy.zeros
遍歷一般是數列,而不是某個文件,如果是文件的話,你需要打開用with open()as 方法
⑨ python中np.zeros什麼意思
zeros(m, n); % 生成一個m*n的零矩陣zeros(m); % 生成一個m*m的零矩陣(即m階方陣)zeros(m, n, k, ...); % 生成一個m*n*k*...的零矩陣zeros(size(A)); % 生成一個與矩陣A的維度一致的零矩陣