cv2监听鼠标事件画图

import cv2
import time
import numpy as np
import sys, os


def draw_circle(event, x, y, flags, p):
    global ix, iy, xys
    if event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        xys.append('{}\t{}\n'.format(x,y))
        cv2.circle(img, (x, y), 3, (0, 0, 0), -1)

if __name__ == '__main__':
    while (1):
        ix, iy, xys = -1, -1, []
        img = np.ones((512, 512, 3), np.uint8) * 255
        cv2.namedWindow('image')
        cv2.setMouseCallback('image', draw_circle)
        while (1):
            cv2.imshow('image', img)
            k = cv2.waitKey(1) & 0xFF
            if k ==ord('s'):
                if not os.path.exists('./photo'):
                    os.mkdir('./photo')
                name = int(time.time())
                with open('./photo/{}.txt'.format(name), 'w') as f:
                    f.writelines(xys)
                cv2.imwrite('./photo/{}.jpg'.format(name), img)
                break
            elif k == ord('c'):
                break
            elif k == 27:
                sys.exit()
        cv2.destroyAllWindows()
# coding=utf-8
from pylab import where, plot, show
from scipy.cluster.vq import vq, kmeans, kmeans2
import matplotlib.pyplot as plt
import numpy as np
import cv2
import sys


def draw_circle(event, x, y, flags, p):
    global ix, iy, xys
    if event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        xys.append([x, y])
        cv2.circle(img, (x, y), 5, (0, 0, 0), -1)

def kmean(features):
    centroids, variance = kmeans2(features, 2)
    print(centroids)
    # 打印聚类中心
    code, distance = vq(features, centroids)
    plt.figure(figsize=(5, 6))
    plt.gca().invert_yaxis()


    ndx0 = where(code == 0)[0]
    plot(features[ndx0, 0], features[ndx0, 1], '*')
    ndx1 = where(code == 1)[0]
    plot(features[ndx1, 0], features[ndx1, 1], 'r.')
    plot(centroids[:, 0], centroids[:, 1], 'go')
    show()


while (1):
    ix, iy, xys = -1, -1, []
    img = np.ones((540, 450, 3), np.uint8) * 255
    cv2.namedWindow('image')
    cv2.setMouseCallback('image', draw_circle)
    while (1):
        cv2.imshow('image', img)
        k = cv2.waitKey(1) & 0xFF
        if k == ord('s'):
            kmean(np.asarray(xys,dtype=np.float))
            break
        elif k == ord('c'):
            break
        elif k == 27:
            sys.exit()
    cv2.destroyAllWindows()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值