在python中集成了两个程序

时间:2016-02-22 16:13:46

标签: python

点击我想要的程序中运行时:

  1. 我的相机初始化
  2. 拍摄前方物体的照片
  3. 检测该图片中的边缘并保存该图片
  4. 将当前图片与我在数据库中已有的图片进行比较
  5. 计算两张图片之间的百分比差异
  6. 这是前三个步骤的代码:

    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 个答案:

答案 0 :(得分: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的调用。[functions]
  • 我非常想把get_image移出函数,但我很懒。
相关问题