2016-02-22 53 views
1

兩個方案時,請單擊上運行的程序我想:Itegration在python

  1. 我的相機初始化
  2. 拍攝物體的圖片在它前面
  3. 檢測的邊緣圖片並保存圖片
  4. 比較已經存在的圖片我已經在數據庫
  5. 當前圖片計算兩個圖片
  6. 之間的百分比差異0

這是我的第3個步驟的代碼:

import numpy as np 
import cv2 
from matplotlib import pyplot as plt 


camera_port = 0 
ramp_frames = 30 
cap = cv2.VideoCapture(camera_port) 
def get_image(): 
retval, im = cap.read() 
return im 

for i in xrange(ramp_frames): 
temp = get_image() 
print("Taking image...") 
# Take the actual image we want to keep 
camera_capture = get_image() 
file = "/Users/Me/Documents/python programs/New/test_image7.jpg" 
# A nice feature of the imwrite method is that it will automatically choose the 
# correct format based on the file extension you provide. Convenient! 
cv2.imwrite(file, camera_capture) 

# You'll want to release the camera, otherwise you won't be able to create a new 
# capture object until your script exits 
del(cap) 

img1=cv2.imread('/Users/Me/Documents/python programs/New/test_image7.jpg',0) 
#height, width, channels = img1.shape 
#res = cv2.resize(img1,(width/2, height/2), interpolation = cv2.INTER_CUBIC) 
#cv2.imshow('image',res) 


edges = cv2.Canny(img1,100,200) 
#plt.subplot(121),plt.imshow(img1,cmap = 'gray') 
#plt.title('Original Image'), plt.xticks([]), plt.yticks([]) 
plt.subplot(122),plt.imshow(edges,cmap = 'gray') 
plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) 

plt.show() 
#plt.save('/Users/Me/Documents/python programs/New/test_image2.jpg',img1) 

cv2.waitKey(0) 
cv2.destroyAllWindows() 

,這裏是代碼得到兩個邊緣圖像之間的差異:

from itertools import izip 
from PIL import Image 

i1 = Image.open("pencil.png") 
i2 = Image.open("eraser2.png") 
assert i1.mode == i2.mode, "Different kinds of images." 
assert i1.size == i2.size, "Different sizes." 

pairs = izip(i1.getdata(), i2.getdata()) 
if len(i1.getbands()) == 1: 
    # for gray-scale jpegs 
    dif = sum(abs(p1-p2) for p1,p2 in pairs) 
else: 
    dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2)) 

ncomponents = i1.size[0] * i1.size[1] * 3 
print "Difference (percentage):", (dif/255.0 * 100)/ncomponents 

現在我的問題是...我如何整合這兩個程序,以及如何在一個程序中編寫整個過程?有人可以幫我嗎?

回答

1

當然,你只需要將所有東西都嵌入到函數中。通常不鼓勵將所有東西都平放在一個文件中。通常情況下,對於腳本,你更喜歡使用的結構如下:

myscript.py

def main(): 
    # Your code here 

if __name__ == '__main__': 
    main() 

而且您現在可以從自己喜歡的命令行工具,python myscript.py調用此腳本。你也可以使用argparse來添加一些位置參數。該結構還允許您編寫單元測試。有關更多詳細信息,請參閱here。現在

,你可以格式化你的代碼,例如:

from itertools import izip 

import numpy as np 
import cv2 
from matplotlib import pyplot as plt 
from PIL import Image 

def take_and_save_picture(im_save): 
    """Take a picture and save it 

    Args: 
    im_save: filepath where the image should be stored 
    """ 
    camera_port = 0 
    ramp_frames = 30 
    cap = cv2.VideoCapture(camera_port) 
    def get_image(): 
    retval, im = cap.read() 
    return im 

    for i in xrange(ramp_frames): 
    temp = get_image() 

    print("Taking image...") 
    # Take the actual image we want to keep 
    camera_capture = get_image() 

    im_save_tmp = im_save + '.tmp' 

    # A nice feature of the imwrite method is that it will automatically choose the 
    # correct format based on the file extension you provide. Convenient! 
    cv2.imwrite(im_save_tmp, camera_capture) 

    # You'll want to release the camera, otherwise you won't be able to create a new 
    # capture object until your script exits 
    del(cap) 

    img1 = cv2.imread(im_save_tmp, 0) 

    edges = cv2.Canny(img1, 100, 200) 
    cv2.imwrite(im_save, edges) 
    cv2.waitKey(0) 
    cv2.destroyAllWindows() 

def compute_edges_diff(im1, im2): 
    """Compute edges diff between to image files. 

    Args: 
    im1: filepath to the first image 
    im2: filepath to the second image 

    Returns: 
    float: percentage of difference between images 
    """ 

    i1 = Image.open(im1) 
    i2 = Image.open(im2) 
    assert i1.mode == i2.mode, "Different kinds of images." 
    assert i1.size == i2.size, "Different sizes." 

    pairs = izip(i1.getdata(), i2.getdata()) 
    if len(i1.getbands()) == 1: 
     # for gray-scale jpegs 
     dif = sum(abs(p1-p2) for p1,p2 in pairs) 
    else: 
     dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2)) 

    ncomponents = i1.size[0] * i1.size[1] * 3 
    diff = (dif/255.0 * 100)/ncomponents 
    return diff 

def main(): 
    capture_img = 'path_to_the_future_captured_img.jpg' 
    img_to_compare = 'the_image_used_for_scoring.jpg' 
    take_and_save_picture(capture_img) 
    diff = compute_edges_diff(im1, im2) 
    print "Difference (percentage):", diff 

if __name__ == '__main__': 
    main() 

正如你所看到的,我有些感動變量函數參數,使他們可以被稱爲/在一個地方設置。我重新編寫了一些可以拍攝圖片的函數,以便中心的臨時jpeg文件具有不同的名稱。你也可以直接從函數中計算圖像之間的差異,這很好。

一些最後的話:

  • 這使您可以進行單元測試的功能。使用內置的幀工作和mock庫來取代對cv2的調用。[功能]
  • 我很想將get_image移出函數,但我很懶。
+0

非常感謝您抽出寶貴時間回答我的問題,....這個解決方案非常完美......我還有一些關於這個的問題..我可以有您的郵件ID嗎?我應該郵寄給你嗎? –

+0

我修改了你給的代碼,它的工作......現在我需要知道如何比較當前圖像與數據庫中的其他10個圖像,並給我的文件與最小的差異...我試過使用這個循環,但它的不工作.. for no_file1範圍(10,100): template = cv2.imread('numbers1/{no_file} .jpg'。格式(no_file = no_file1),0) –

+0

「不工作」非常模糊,但如果您有10張圖像,爲什麼不使用範圍(10)而不是範圍(10,100)? –