如何将这两个功能合并为一个? [python 3.]

时间:2018-04-06 08:38:47

标签: python python-3.x image opencv mouse

我开始学习python(通过anaconda)已有几周了。我已经开始为我的工作开发一些应用程序的个人代码。 所以问题是下一个,我有两个函数draw_rectanglemagnification,每个函数使用不同的mouse_handler。 正如您在代码中看到的,两个函数都是相同的,所以我想要做的是将它们合并到一个函数中(尝试创建更好的代码结构)。

最后,我通过以下方式在另一个脚本中调用这些函数:

data['image_right'], rectangle['right'] = draw_rectangle(data['image_right'])

magnification = magnification(data['image_left'])

以下是功能:

def mouse_handler(action, x, y, flags,img) :
    # Action to be taken when left mouse button is pressed
    if action==cv2.EVENT_LBUTTONDOWN:
        rectangle.append([x,y])
    # Action to be taken when left mouse button is released
    elif action==cv2.EVENT_LBUTTONUP:
        rectangle.append([x,y])

def draw_rectangle(img):
    global rectangle
    rectangle = []
    #Create the window to show image
    cv2.namedWindow("Image",cv2.WINDOW_NORMAL)  
    cv2.setMouseCallback("Image", mouse_handler, img)
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()    
    img = img[rectangle[0][1]:rectangle[1][1],rectangle[0][0]:rectangle[1][0]]

    return img, rectangle


def mouse_handler2(action, x, y, flags,img) :
    # Action to be taken when left mouse button is pressed
    if action==cv2.EVENT_LBUTTONDOWN:
        coordinates.append([x,y])
    # Action to be taken when left mouse button is released
    elif action==cv2.EVENT_LBUTTONUP:
        coordinates.append([x,y])

def magnification(img):
     global coordinates
     coordinates = []
     imgcopy = img.copy()
     #Create the window to show image
     cv2.namedWindow("Image",cv2.WINDOW_NORMAL)
     cv2.setMouseCallback("Image", mouse_handler2, imgcopy)
     cv2.putText(imgcopy, "Click/unclick", (int(imgcopy.shape[1]/4), int(imgcopy.shape[0]/2)), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 0), 3)
     cv2.imshow("Image", imgcopy)
     cv2.waitKey(0)
     cv2.destroyAllWindows()

     magnification = 10/np.sqrt( np.power((coordinates[0][1]-coordinates[1][1]),2)+ np.power((coordinates[0][0]-coordinates[1][0]),2))

     return magnification

0 个答案:

没有答案
相关问题