目前剛接觸python
以python撰寫了一段Sobel影像處理,程式碼如下
===================================================
import cv2
import numpy as np
img=cv2.imread("/home/chenposhao/Desktop/IMAGE/cameraman.tif",0)
[row,col]=img.shape
resx=np.zeros((row,col),np.uint8)
kernalx=np.array([[1,2,1],[0,0,0],[-1,-2,-1]])
kernaly=np.array([[1,0,-1],[2,0,-2],[1,0,-1]])
for x in range(row):
for y in range(col):
if x==0 or x==row-1 or y==0 or y==col-1:
pass
else:
subxsum=0
subysum=0
for i in range(-1,2):
for j in range(-1,2):
newx=img[x+i,y+j]*kernalx[i+1,j+1]
subxsum=subxsum+newx
newy=img[x+i,y+j]*kernaly[i+1,j+1]
subysum=subysum+newy
respixel=abs(subxsum+subysum/2)
if respixel>255:
respixel=255
elif respixel<0:
respixel=0
resx[x,y]=respixel
cv2.imshow("IMAGE",img)
cv2.imshow("SOBELX",resx)
cv2.waitKey(0)
cv2.destroyAllWindows()
================================================================
首先要先說,跑的圖片是256*256
我知道CV有SOBEL函式庫可以用,
但因為用他的函式庫發現他並沒有將所計算的像素取絕對值
因此有方向性的問題,為了驗證才寫此程式碼
但發現這個程式碼再執行的時候不如預期的快
從中間的for x in range(row): 到 resx[x,y]=respixel
整個FORLOOP跑完要5.5秒左右
VB,C幾毫秒即可跑完
想問一下這是python所必須要克服的事情嘛?
因為剛接觸Python,早有相傳他因為直譯所以速度慢
但想不到落差有些許的大
還是說其實這是能改善的?
謝謝