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()