def test_grid():
m = StupidMonkey({'touch':10})
poss = []
while True:
pos = m.get_touch_point()
if not pos:
break
poss.append(pos)
print 'grid point count:', len(poss)
import cv2
import numpy
img = numpy.zeros((1920, 1080))
for x,y in poss:
img[x,y] = 255
img = cv2.resize(img, (540, 960))
cv2.imshow('grid', img)
cv2.waitKey()
python类waitKey()的实例源码
def main(serial=None, host=None, port=None):
d = atx.connect(serial, host=host, port=port)
while True:
pilimg = d.screenshot()
cv2img = imutils.from_pillow(pilimg)
# cv2img = cv2.imread('tmp.png')
# cv2.imwrite('tmp.png', cv2img)
cv2img = cv2.resize(cv2img, fx=0.5, fy=0.5, dsize=(0, 0))
pt = choose_point(cv2img)
print 'click:', pt
if pt:
x, y = pt
d.click(2*x, 2*y)
cv2.waitKey(100)
# import time
# time.sleep(0.1)
def draw_boxes(im, bboxes, is_display=True, color=None, caption="Image", wait=True):
"""
boxes: bounding boxes
"""
im=im.copy()
for box in bboxes:
if color==None:
if len(box)==5 or len(box)==9:
c=tuple(cm.jet([box[-1]])[0, 2::-1]*255)
else:
c=tuple(np.random.randint(0, 256, 3))
else:
c=color
cv2.rectangle(im, tuple(box[:2]), tuple(box[2:4]), c)
if is_display:
cv2.imshow(caption, im)
if wait:
cv2.waitKey(0)
return im
def plot_conf_mat(densmap_name):
fig = plt.figure(figsize = (20,20))
plt.clf()
ax = fig.add_subplot(111)
#ax.set_aspect(1)
densmap = np.fromfile(densmap_name, np.float32)
densmap = densmap.reshape(227, 227)
densmap *= 100
densmap[densmap > 1] = 1
res = ax.imshow(densmap, cmap = plt.cm.jet,
interpolation = 'nearest')
plt.savefig('density.jpg')
img = cv2.imread("density.jpg")
img = cv2.resize(img, (227,227))
cv2.imshow("i", img)#
cv2.waitKey(0)
#plt.show()
def pick_corrs(images, n_pts_to_pick=4):
data = [ [[], 0, False, False, False, image, "Image %d" % i, n_pts_to_pick]
for i, image in enumerate(images)]
for d in data:
win_name = d[6]
cv2.namedWindow(win_name)
cv2.setMouseCallback(win_name, corr_picker_callback, d)
cv2.startWindowThread()
cv2.imshow(win_name, d[5])
key = None
while key != '\n' and key != '\r' and key != 'q':
key = cv2.waitKey(33)
key = chr(key & 255) if key >= 0 else None
cv2.destroyAllWindows()
if key == 'q':
return None
else:
return [d[0] for d in data]
def detect(imgfile):
origimg = cv2.imread(imgfile)
img = preprocess(origimg)
img = img.astype(np.float32)
img = img.transpose((2, 0, 1))
net.blobs['data'].data[...] = img
out = net.forward()
box, conf, cls = postprocess(origimg, out)
for i in range(len(box)):
p1 = (box[i][0], box[i][1])
p2 = (box[i][2], box[i][3])
cv2.rectangle(origimg, p1, p2, (0,255,0))
p3 = (max(p1[0], 15), max(p1[1], 15))
title = "%s:%.2f" % (CLASSES[int(cls[i])], conf[i])
cv2.putText(origimg, title, p3, cv2.FONT_ITALIC, 0.6, (0, 255, 0), 1)
cv2.imshow("SSD", origimg)
k = cv2.waitKey(0) & 0xff
#Exit if ESC pressed
if k == 27 : return False
return True
def test_minicap():
from atx.drivers.android_minicap import AndroidDeviceMinicap
cv2.namedWindow("preview")
d = AndroidDeviceMinicap()
while True:
try:
h, w = d._screen.shape[:2]
img = cv2.resize(d._screen, (w/2, h/2))
cv2.imshow('preview', img)
key = cv2.waitKey(1)
if key == 100: # d for dump
filename = time.strftime('%Y%m%d%H%M%S.png')
cv2.imwrite(filename, d._screen)
except KeyboardInterrupt:
break
cv2.destroyWindow('preview')
def test_grid():
m = StupidMonkey({'touch':10})
poss = []
while True:
pos = m.get_touch_point()
if not pos:
break
poss.append(pos)
print 'grid point count:', len(poss)
import cv2
import numpy
img = numpy.zeros((1920, 1080))
for x,y in poss:
img[x,y] = 255
img = cv2.resize(img, (540, 960))
cv2.imshow('grid', img)
cv2.waitKey()
def main(serial=None, host=None, port=None):
d = atx.connect(serial, host=host, port=port)
while True:
pilimg = d.screenshot()
cv2img = imutils.from_pillow(pilimg)
# cv2img = cv2.imread('tmp.png')
# cv2.imwrite('tmp.png', cv2img)
cv2img = cv2.resize(cv2img, fx=0.5, fy=0.5, dsize=(0, 0))
pt = choose_point(cv2img)
print 'click:', pt
if pt:
x, y = pt
d.click(2*x, 2*y)
cv2.waitKey(100)
# import time
# time.sleep(0.1)
def main(args):
saveFace = None;
cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
faces = face_cascade.detectMultiScale(frame, 1.3, 5)
if len(faces) > 0:
saveFace = frame
break;
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
cv2.imwrite('C:/Users/USER/Desktop/facenet-RealTime/src/face_data/saveFace.jpg',frame)
mypath = 'C:/Users/USER/Desktop/facenet-RealTime/src/face_data'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
myImage = []
for file in onlyfiles:
isImage = None
file = mypath + '/' + file
isImage = imghdr.what(file)
if isImage != None:
myImage.append(file)
#begin facenet
cp.main(args,myImage);
def evaluate(img_col, args):
numpy.seterr(all='ignore')
assert isinstance(img_col, numpy.ndarray), 'img_col must be a numpy array'
assert img_col.ndim == 3, 'img_col must be a color image ({0} dimensions currently)'.format(img_col.ndim)
assert isinstance(args, argparse.Namespace), 'args must be of type argparse.Namespace not {0}'.format(type(args))
img_gry = cv2.cvtColor(img_col, cv2.COLOR_RGB2GRAY)
rows, cols = img_gry.shape
crow, ccol = rows/2, cols/2
f = numpy.fft.fft2(img_gry)
fshift = numpy.fft.fftshift(f)
fshift[crow-75:crow+75, ccol-75:ccol+75] = 0
f_ishift = numpy.fft.ifftshift(fshift)
img_fft = numpy.fft.ifft2(f_ishift)
img_fft = 20*numpy.log(numpy.abs(img_fft))
if args.display and not args.testing:
cv2.destroyAllWindows()
scripts.display('img_fft', img_fft)
scripts.display('img_col', img_col)
cv2.waitKey(0)
result = numpy.mean(img_fft)
return img_fft, result, result < args.thresh
def visualize_image(image, name="Image", resize=False, save_image=False, path=None):
"""Helper function to visualize and save any image"""
image = image.reshape([IMAGE_WIDTH, IMAGE_HEIGHT])
image = image.astype(np.uint8)
if resize:
image = cv2.resize(image, (IMAGE_WIDTH * 10, IMAGE_HEIGHT * 10))
cv2.imshow(name, image)
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()
if save_image:
assert path is not None
cv2.imwrite(path, image)
def image_preview(image):
cv2.imshow('Image preview', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def display_solution(square_borders, start_grid, solution, image):
""" Writes the solution to an image and displays said image.
Params:
square_borders -- A list containing the borders of all squares
start_grid -- A list containing the sudoku starting values
solution -- A list containing the sudoku solution
image -- The image to write to """
cur_row = 0
cur_col = 0
for i, b in enumerate(square_borders):
x, y, x2, y2 = b # Tuple unpacking
# Calculate bottom-left position for text
text_x, text_y = ((x2+x) / 2) - 10, ((y2+y) / 2) + 10
# Bottom-left corner for text position
org = (text_x, text_y)
# Only write text if the position was not set in the start_grid
if start_grid[cur_row][cur_col] is 0:
value = str(solution[cur_row][cur_col])
cv2.putText(
img=image,
text=value,
org=org,
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1,
color=(0, 255, 0),
thickness=2)
cur_col += 1
if cur_col % 9 == 0:
cur_row += 1
cur_col = 0
cv2.imshow('Solution', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def process_image(image):
array_image = numpy.array(image)
array_image = cv2.resize(array_image, (0,0), fx=2, fy=2)
#cv2.imshow('image', array_image)
#cv2.waitKey(0)
image = PIL.Image.fromarray(array_image)
return(image)
def online_receive_frame(viewer_state, episode):
logger.info('Waiting for message...')
if not viewer_state.conn.poll(1000.0):
raise EnvironmentError("Failed to receive message!")
msg = viewer_state.conn.recv()
if isinstance(msg, frame_module.Frame):
viewer_state.current_frame = msg
episode.frames.append(viewer_state.current_frame)
elif msg['msg'] == 'init':
viewer_state.prev_frame = msg
viewer_state.action_set = msg['action_set']
viewer_state.episode_num_in_session += 1
print('Initial message received')
print('... got action_set: {}'.format(viewer_state.action_set))
print('... episode_num: {}'.format(viewer_state.episode_num_in_session))
viewer_state.env_id = msg['env_id']
viewer_state.skip_frame = True
elif msg['msg'] == 'close':
viewer_state.conn.close()
viewer_state.close = True
elif msg['msg'] == 'done':
viewer_state.frame_index = 0
proceed = input('Proceed to next episode?')
if proceed != 'y':
viewer_state.EXIT = True
while True:
k = cv2.waitKey(viewer_state.delay) & 0xFF
if k == 255: break
viewer_state.skip_episode = True
else:
print('Unknown message received: {}'.format(msg))
viewer_state.skip_frame = True
return viewer_state, episode
def test(self):
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
self.saver_z.restore(sess, self.encode_z_model)
self.saver_y.restore(sess, self.encode_y_model)
realbatch_array, _ = MnistData.getNextBatch(self.ds_train, self.label_y, 0, 50,
self.batch_size)
output_image , label_y = sess.run([self.fake_images,self.e_y], feed_dict={self.images: realbatch_array})
#one-hot
#label_y = tf.arg_max(label_y, 1)
print label_y
save_images(output_image , [8 , 8] , './{}/test{:02d}_{:04d}.png'.format(self.sample_path , 0, 0))
save_images(realbatch_array , [8 , 8] , './{}/test{:02d}_{:04d}_r.png'.format(self.sample_path , 0, 0))
gen_img = cv2.imread('./{}/test{:02d}_{:04d}.png'.format(self.sample_path , 0, 0), 0)
real_img = cv2.imread('./{}/test{:02d}_{:04d}_r.png'.format(self.sample_path , 0, 0), 0)
cv2.imshow("test_EGan", gen_img)
cv2.imshow("Real_Image", real_img)
cv2.waitKey(-1)
print("Test finish!")
def image_detector(self, imname, wait=0):
detect_timer = Timer()
image = cv2.imread(imname)
detect_timer.tic()
result = self.detect(image)
detect_timer.toc()
print('Average detecting time: {:.3f}s'.format(detect_timer.average_time))
self.draw_result(image, result)
cv2.imshow('Image', image)
cv2.waitKey(wait)
def getFrame(self):
ret = False
count = 0
while not ret:
# Capture frame-by-frame
count = count + 1
ret, frame = self.cap.read()
if cv2.waitKey(1) & 0xFF == ord('q'):
return (False, None)
if count > 10:
return (False, None)
return (True, frame)
def showFrame(self, frame):
# Display the resulting frame
cv2.imshow(self.frame_name, frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
return False
else:
return True