繁体   English   中英

如何使用 opencv 将两个鼠标坐标 [(x0,y0),(x1,y1)] 导出到 python 中的 txt 文件

[英]How to export two mouse coordinates [(x0,y0),(x1,y1)] to a txt file in python, with opencv

我目前正在研究 object 检测程序。 我最初的工作是读取鼠标坐标并将它们导出到文本文件(用于进一步处理)。

我尝试了另一个链接中的一些代码( https://www.pyimagesearch.com/2015/03/09/capturing-mouse-click-events-with-python-and-opencv/ )。 它确实有效,但我不知道如何将这些文件导出功能添加到原始代码中。 任何帮助都感激不尽!

当我在终端中运行类似“python click_and_crop.py --image img_0001_c0.pgm”的命令时,我希望得到一个内容为“355、53、424、107”的txt文件,这样将来我可以调用它function 从更多图片中获取更多鼠标坐标。但是,我得到了“[[(299, 190), (421, 285)]]”(没有“”)。

# USAGE
# python click_and_crop.py --image img_0001_c0.pgm

# import the necessary packages
import argparse
import cv2

# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False
str1 = []
path_name = 'mouseCoordinates.txt'

def click_and_crop(event, x, y, flags, param):
    # grab references to the global variables
    global refPt, cropping

    # if the left mouse button was clicked, record the starting
    # (x, y) coordinates and indicate that cropping is being
    # performed
    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True

    # check to see if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates and indicate that
        # the cropping operation is finished
        refPt.append((x, y))
        cropping = False

        # draw a rectangle around the region of interest
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        print(refPt[0][0], refPt[0][1], refPt[1][0], refPt[1][1])
        str1.append(refPt)
        cv2.imshow("image", image)
        mouseXY = open(path_name, 'w')
        mouseXY.write(str(str1))
        mouseXY.close()


# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image, clone it, and setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)

# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

    # if the 'r' key is pressed, reset the cropping region
    if key == ord("r"):
        image = clone.copy()

    # if the 'c' key is pressed, break from the loop
    elif key == ord("c"):
        break

# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(refPt) == 2:
    roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
    cv2.imshow("ROI", roi)
    cv2.waitKey(0)

# close all open windows
cv2.destroyAllWindows()

# USAGE
# python click_and_crop.py --image img_0001_c0.pgm

# import the necessary packages
import argparse
import cv2

# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False
str1 = []
path_name = 'mouseCoordinates.txt'

def click_and_crop(event, x, y, flags, param):
    # grab references to the global variables
    global refPt, cropping

    # if the left mouse button was clicked, record the starting
    # (x, y) coordinates and indicate that cropping is being
    # performed
    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True

    # check to see if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates and indicate that
        # the cropping operation is finished
        refPt.append((x, y))
        cropping = False

        # draw a rectangle around the region of interest
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        print(refPt[0][0], refPt[0][1], refPt[1][0], refPt[1][1])
        str1.append(refPt[0])
        cv2.imshow("image", image)
        mouseXY = open(path_name, 'w')
        mouseXY.write()
        mouseXY.close()


# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image, clone it, and setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)

# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

    # if the 'r' key is pressed, reset the cropping region
    if key == ord("r"):
        image = clone.copy()

    # if the 'c' key is pressed, break from the loop
    elif key == ord("c"):
        break

# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(refPt) == 2:
    roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
    cv2.imshow("ROI", roi)
    cv2.waitKey(0)

# close all open windows
cv2.destroyAllWindows()

您可以编写类似这样的 function 以将鼠标指针作为输入并将 append 写入文件。

def write_to_file(x, y, a, b):
    '''
    Writes the mouse coordinates to a text file
    '''
    # open the mouse coordinates
    with open('mouseCoordinates.txt', 'a') as f:
        # create a string ready to write to the file
        coordinates = str(x) + ',' + str(y) + ',' + str(a) + ',' + str(b) + '\n'

        # write to file
        f.write(coordinates)

然后你会输入这样的坐标?

write_to_file(refPt[0][0], refPt[0][1], refPt[1][0], refPt[1][1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM