【问题标题】:I need to save the image coordinates in a txt file by clicking on mouse我需要通过单击鼠标将图像坐标保存在 txt 文件中
【发布时间】:2019-01-13 22:59:38
【问题描述】:

怎么了,伙计们。我在编程方面非常初学者。所以,我需要创建一个代码,点击图像并保存它的坐标。我需要在 python+opencv 中制作它。我已经做了一些事情,但是它没有保存它的坐标。 首先,打开一张图片。 其次,点击像素。 三、将像素信息(列、行​​)保存在txt文件中。

import matplotlib.pyplot as plt
import numpy as np
import cv2

def callback(event):
    print ('event.x, event.y')

fig, ax = plt.subplots()

fig.canvas.callbacks.connect('button_press_event', callback)
def callback(event):
    print ('event.xdata, event.ydata')




img = cv2.imread('/home/dgt/Pictures/1.jpeg',-1)
plt.imshow(img, cmap='gray', interpolation='bicubic')



plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

  • 你正在重新定义callback,所以第一个“版本”当然丢失了......
  • 那么,我该怎么办?

标签: python opencv ubuntu


【解决方案1】:

使用此脚本,您可以单击图像,并将单击位置保存到电子表格中:

import cv2, numpy as np

# Path to source video:
output_path = '/home/stephen/Desktop/clicks.csv'

# Mouse callback function
global click_list
positions, click_list = [], []
def callback(event, x, y, flags, param):
    if event == 1: click_list.append((x,y))
cv2.namedWindow('img')
cv2.setMouseCallback('img', callback)

img = cv2.imread('/home/stephen/Desktop/test214.png')

# Mainloop - show the image and collect the data
while True:
    cv2.imshow('img', img)    
    # Wait, and allow the user to quit with the 'esc' key
    k = cv2.waitKey(1)
    # If user presses 'esc' break 
    if k == 27: break        
cv2.destroyAllWindows()

# Write data to a spreadsheet
import csv
with open(output_path, 'w') as csvfile:
    fieldnames = ['x_position', 'y_position']
    writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writer.writeheader()
    for position in click_list:
        x, y = position[0], position[1]
        writer.writerow({'x_position': x, 'y_position': y})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2023-01-30
    • 2014-05-23
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多