python中两个程序的集成

python中两个程序的集成,python,Python,在我想要的程序中单击“运行”时: 我的相机需要初始化 给它前面的物体拍照 检测该图片中的边缘并保存该图片 将当前图片与数据库中已有的图片进行比较 计算两张图片之间的百分比差异 以下是我的前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_imag

在我想要的程序中单击“运行”时:

  • 我的相机需要初始化
  • 给它前面的物体拍照
  • 检测该图片中的边缘并保存该图片
  • 将当前图片与数据库中已有的图片进行比较
  • 计算两张图片之间的百分比差异
  • 以下是我的前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
    

    现在我的问题是。。。如何集成这两个程序,如何在一个程序中编写整个过程?有人能帮我吗?

    当然,您只需要将所有内容嵌入函数中即可。通常不鼓励将所有内容平装成一个文件。通常,对于脚本,您更喜欢使用以下结构:

    myscript.py

    def main():
        # Your code here
    
    if __name__ == '__main__':
        main()
    
    现在,您可以使用
    python myscript.py
    从您最喜欢的命令行工具调用此脚本。还可以使用argparse添加一些位置参数。该结构还允许您编写单元测试。有关更多详细信息,请参阅

    现在,您可以将代码格式化为:

    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
      移出函数,但我很懒

    非常感谢您抽出时间回答我的问题,。。。。这一切都很顺利。。。关于这一点,我还有几个问题。。能给我你的邮箱号吗?我可以把它寄给你吗?我修改了你给的代码,它工作了。。。现在我需要知道如何将当前图像与数据库中的10个其他图像进行比较,并给我差异最小的文件。。。我试着使用这个循环,但它不起作用。。对于范围(10100)中的no_file1:template=cv2.imread('numbers1/{no_file}.jpg'。格式(no_file=no_file1),0)“不工作”非常模糊,但是如果有10个图像,为什么不使用范围(10)而不是范围(10100)?。。。。我需要我的代码将当前图像与特定文件夹中的10个图像进行比较。。。如果一个文件中有10张图片,而现在只捕获了一张图片。。。我需要系统将捕获的图像与该特定文件夹中的所有10个图像进行比较,并将差异百分比最小的图像带给我。。。。如何做到这一点?使用
    for
    循环迭代10幅图像的名称,并对每幅图像运行
    compute\u edges\u diff
    。跟踪哪张图片给你的分数是最低还是最高,并输出这张图片。