gpt4 book ai didi

python - python 中两个程序的集成

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:20 25 4
gpt4 key购买 nike

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

  1. 我的相机要初始化
  2. 给前面的物体拍张照片
  3. 检测该图片中的边缘并保存该图片
  4. 将当前图片与数据库中已有的图片进行比较
  5. 计算两张图片之间的百分比差异

这是我前 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 添加一些位置参数。该结构还允许您编写单元测试。请参阅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 移出该函数,但我很懒。

关于python - python 中两个程序的集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35558477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com