def add_person(people_folder, shape):
""" Funtion to add pictures of a person
"""
person_name = input('What is the name of the new person: ').lower()
folder = people_folder + person_name
if not os.path.exists(folder):
input("I will now take 20 pictures. Press ENTER when ready.")
os.mkdir(folder)
video = VideoCamera()
detector = FaceDetector('face_recognition_system/frontal_face.xml')
counter = 1
timer = 0
cv2.namedWindow('Video Feed', cv2.WINDOW_AUTOSIZE)
cv2.namedWindow('Saved Face', cv2.WINDOW_NORMAL)
while counter < 21:
frame = video.get_frame()
face_coord = detector.detect(frame)
if len(face_coord):
frame, face_img = get_images(frame, face_coord, shape)
# save a face every second, we start from an offset '5' because
# the first frame of the camera gets very high intensity
# readings.
if timer % 100 == 5:
cv2.imwrite(folder + '/' + str(counter) + '.jpg',
face_img[0])
print ('Images Saved:' + str(counter))
counter += 1
cv2.imshow('Saved Face', face_img[0])
cv2.imshow('Video Feed', frame)
cv2.waitKey(50)
timer += 5
else:
print ("This name already exists.")
sys.exit()
python类WINDOW_NORMAL的实例源码
start_face_recon_app.py 文件源码
项目:Smart-Surveillance-System-using-Raspberry-Pi
作者: OmkarPathak
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def generateMask(img):
blured_img = getBlurImage(img)
hsv, hue, sat, val = getHSVImage(blured_img)
# binary_img_hsv = binaryIMG(blured_img)
cv2.namedWindow('hsv', cv2.WINDOW_NORMAL)
cv2.imshow("hsv", hsv)
hsv += 35
cv2.namedWindow('hsv-inc', cv2.WINDOW_NORMAL)
cv2.imshow("hsv-inc", hsv)
gray = getBinaryImage(hsv)
filtered_img = getFilterImage(gray)
opening_img = getOpeningImage(filtered_img)
closing_img = getClosingImage(opening_img)
canny_edge_img = autoCannyEdgeDetection(closing_img)
contours, contour_img = getContourImage(canny_edge_img)
binary_line_img = drawLines(contour_img, contours)
# convex_img = drawConvexHull(hsv, contours)
dilation_img = getDilationImage(binary_line_img)
cv2.namedWindow('gray', cv2.WINDOW_NORMAL)
cv2.imshow("gray", gray)
cv2.namedWindow('canny-edge', cv2.WINDOW_NORMAL)
cv2.imshow("canny-edge", canny_edge_img)
cv2.namedWindow('contour', cv2.WINDOW_NORMAL)
cv2.imshow("contour", contour_img)
cv2.namedWindow('dilation', cv2.WINDOW_NORMAL)
cv2.imshow("dilation", dilation_img)
# cv2.namedWindow('convex', cv2.WINDOW_NORMAL)
# cv2.imshow("convex", convex_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return dilation_img
def main():
img = cv2.imread("../data/aug/train/benign/ISIC_0000201.jpg_aug0.jpg")
# img = cv2.imread("../data/aug/train/benign/ISIC_0000011.jpg_aug0.jpg")
# img = cv2.imread("../data/aug/train/benign/ISIC_0000113.jpg_aug0.jpg")
# img = cv2.imread("../data/aug/train/benign/ISIC_0009344.jpg_aug12.jpg")
mask = generateMask(img)
final = extractRegion(img, mask)
cv2.namedWindow('final', cv2.WINDOW_NORMAL)
cv2.imshow("final", final)
cv2.waitKey(0)
cv2.destroyAllWindows()
def get_image_detections(path):
ssd = SSD()
global i2name
i2name = pickle.load(open("i2name.p", "rb"))
#cv2.namedWindow("outputs", cv2.WINDOW_NORMAL)
sample = io.imread(path)[:, :, :3]
boxes_, confidences_ = ssd.single_image(sample)
return boxes_, confidences_
def video():
global face_token
ft=cv2.freetype.createFreeType2()
ft.loadFontData(fontFileName='./data/font/simhei.ttf',id =0)
face_cascade = cv2.CascadeClassifier('./data/cascades/haarcascade_frontalface_alt.xml')
camera=cv2.VideoCapture(0)
count = 0
while(True):
ret,frame=camera.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray,1.3,5)
for(x,y,w,h) in faces:
img =cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)
if count%5<2:
f=cv2.resize(gray[y:y+h,x:x+w],(200,200))
cv2.imwrite('./data/temp/temp.pgm',f)
result=FaceAPI.searchItoI(image_file='./data/temp/temp.pgm')
if len(result)==4:
break
if result["results"][0]["confidence"] >= 80.00:
print result["results"][0]["confidence"]
face_token=result["results"][0]["face_token"]
detail=get_detail()
# shutil.copyfile("./data/temp/temp.pgm","./data/at/%s/%s.pgm"%(detail,time.strftime('%Y%m%d%H%M%S')))
print detail
ft.putText(img=img,text=detail[1], org=(x, y - 10), fontHeight=60,line_type=cv2.LINE_AA, color=(0,255,165), thickness=2, bottomLeftOrigin=True)
# count+=1
else:
print"Unknow face"
cv2.putText(img,"Unknow", (x, y - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,225), 2)
count +=1
print count
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.imshow("image",frame)
if cv2.waitKey(1000 / 12)&0xff==ord("q"):
break
camera.release()
cv2.destroyAllWindows()
def get_seg_result(self,det_preds,imgs,imgname_list,stride=128):
with tf.Graph().as_default():
image_batch = tf.placeholder(dtype=tf.float32,shape=[None,stride,stride,3],name = 'image_batch_seg')
is_training = tf.placeholder(tf.bool, shape=[], name='is_training')
with tf.variable_scope('Seg_Net'):
seg_net = Seg_Net()
logits = seg_net.inference(image_batch, is_training)
seg_pred = seg_net.eval(logits=logits)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
saver.restore(sess,SEG_MODEL_PATH)
print "Restored model parameters from {}".format(SEG_MODEL_PATH)
all_patch_np_list,all_patch_cood_list = self._get_seg_data(det_preds,imgs,stride)
for i,(patchs,coods) in enumerate(zip(all_patch_np_list,all_patch_cood_list)):
num = int(math.ceil(float(patchs.shape[0])/SEG_BATCH_SIZE))
mask = np.zeros(shape=(imgs.shape[1],imgs.shape[2]),dtype=np.uint8)
for j in range(num):
start = j*SEG_BATCH_SIZE
end = min((j+1)*SEG_BATCH_SIZE,patchs.shape[0])
input_batch = patchs[start:end]
input_coods = coods[start:end]
seg_preds, = sess.run([seg_pred],feed_dict={image_batch:input_batch,is_training:False})
print 'seg_preds.shape', seg_preds.shape
seg_preds = np.squeeze(seg_preds,axis=3)
for k in range(seg_preds.shape[0]):
y_start = input_coods[k][0]
x_start = input_coods[k][1]
mask[y_start*stride:(y_start+1)*stride,x_start*stride:(x_start+1)*stride] = seg_preds[k]
mask[np.where(mask==1)] = 255
# cv2.namedWindow('mask',cv2.WINDOW_NORMAL)
# cv2.imshow('mask',mask)
# cv2.waitKey(0)
if not os.path.exists(SAVE_SEG_DIR):
os.makedirs(SAVE_SEG_DIR)
cv2.imwrite(os.path.join(SAVE_SEG_DIR,imgname_list[i]),mask)
def main():
root = './resize_4096'
save_dir = './generate_defect1_again'
dataset_generate(root,save_dir)
# cv2.imshow("img", img)
# cv2.waitKey(0)
# def main():
# img = cv2.imread('./def_1.png',cv2.cv.CV_LOAD_IMAGE_GRAYSCALE)
# print img.shape
# cv2.namedWindow('label',cv2.WINDOW_NORMAL)
# cv2.namedWindow('img',cv2.WINDOW_NORMAL)
# # label = generate_defect_img(img,1,5)
# label_img = np.zeros_like(img)
# #generate_blur(img,label_img,1,(0.05,0.1),(0.05,0.1))
# #generate_scratch(img,label_img,1,(0.0001,0.002),5,(0.005,0.4))
# #generate_spot(img,label_img,1,(0.0001,0.0005),2)
# cv2.imshow("label", label_img)
# cv2.imshow("img", img)
# cv2.waitKey(0)
def ViewScreenCaptureStream(self): #not developed it much, it requires more work to be done to be fully functional
frames = []
frameFileNames = [fN for fN in self.ftp.nlst("\\"+ self.directories[self.dirNum] +"\\vv") if fN != "s.mm"]
if frameFileNames:
for fileName in frameFileNames:
retrievedData = []
self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] +"\\vv\\" + fileName, retrievedData.append)
tempBuff = StringIO.StringIO()
tempBuff.write(XorText("".join(retrievedData),self.xorMap))
tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
printscreen_pil = Image.open(tempBuff)
printscreen_pil = printscreen_pil.resize((printscreen_pil.size[0],printscreen_pil.size[1]), Image.ANTIALIAS)
frame = np.array(printscreen_pil.getdata(),dtype=np.uint8).reshape((printscreen_pil.size[1],printscreen_pil.size[0],3))
#frames.append(frame)
cv2.namedWindow("window", cv2.WINDOW_NORMAL)
cv2.imshow('window', frame)
#cv2.resizeWindow('window', 200,200)
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
print "No frames available"
return
'''
for frame in frames:
cv2.namedWindow("window", cv2.WINDOW_NORMAL)
cv2.imshow('window', frame)
#cv2.resizeWindow('window', 200,200)
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
'''
def main():
# Read in image with the shape (rows, cols, channels)
im = imread('./lena.small.jpg')
im = np.array(im) / 255.
invSpatialStdev = float(1. / 5.)
invColorStdev = float(1. / .125)
# Construct the position vectors out of x, y, r, g, and b.
positions = np.zeros((im.shape[0], im.shape[1], 5), dtype='float32')
for r in range(im.shape[0]):
for c in range(im.shape[1]):
positions[r, c, 0] = invSpatialStdev * c
positions[r, c, 1] = invSpatialStdev * r
positions[r, c, 2] = invColorStdev * im[r, c, 0]
positions[r, c, 3] = invColorStdev * im[r, c, 1]
positions[r, c, 4] = invColorStdev * im[r, c, 2]
out = PermutohedralLattice.filter(im, positions)
logging.info('Done')
out -= out.min()
out /= out.max()
im -= im.min()
im /= im.max()
out = cv2.cvtColor(out.astype('float32'), cv2.COLOR_RGB2BGR)
im = cv2.cvtColor(im.astype('float32'), cv2.COLOR_RGB2BGR)
cv2.namedWindow('original', cv2.WINDOW_NORMAL)
cv2.namedWindow('filtered', cv2.WINDOW_NORMAL)
cv2.imshow('original', im)
cv2.imshow('filtered', out)
cv2.waitKey(0)
def evaluate_images():
tb = TB()
cv2.namedWindow("outputs", cv2.WINDOW_NORMAL)
test_loader = sLoader.SVT('./svt1/train.xml', './svt1/test.xml')
while True:
imgs, anns = test_loader.nextBatch(3,'test')
pred_labels_f, pred_locs_f, step = tb.sess.run([tb.pred_labels, tb.pred_locs, tb.global_step],
feed_dict={tb.imgs_ph: imgs, tb.bn: False})
boxes_, confidences_ = matcher.format_output(pred_labels_f[0], pred_locs_f[0])
draw_outputs(imgs[0], boxes_, confidences_, wait=0)
def get_image_detections(path):
tb = TB()
#cv2.namedWindow("outputs", cv2.WINDOW_NORMAL)
sample = cv2.imread(path)[:, :, :3]
sample = cv2.resize(sample, (300,300))
boxes_, confidences_ = tb.single_image(sample)
return boxes_, confidences_
def show_image(img, ms = 0):
cv2.namedWindow("Window", cv2.WINDOW_NORMAL)
cv2.imshow("Window", img)
cv2.waitKey(ms)
cv2.destroyAllWindows()
def show_image(img, ms = 0):
cv2.namedWindow("Window", cv2.WINDOW_NORMAL)
cv2.imshow("Window", img)
cv2.waitKey(ms)
cv2.destroyAllWindows()
def show_image(img, ms = 0):
cv2.namedWindow("Window", cv2.WINDOW_NORMAL)
cv2.imshow("Window", img)
cv2.waitKey(ms)
cv2.destroyAllWindows()
def Crop(img,title):
def onmouse(event,x,y,flags,param):
global ix,iy,roi,drawing
# Draw Rectangle
if event == cv2.EVENT_RBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,abs(ix-x),abs(iy-y))
elif event == cv2.EVENT_RBUTTONUP:
drawing = False
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,x,y)
roi.extend(rect)
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.setMouseCallback(title,onmouse)
print ("Right click and hold to draw a single rectangle ROI, beginning at the top left corner of the desired area. A blue box should appear. Hit esc to exit screen. Window can be resized by selecting borders.")
while True:
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.imshow(title,img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
print(roi)
return(roi)
def Crop(img,title):
def onmouse(event,x,y,flags,param):
global ix,iy,roi,drawing
# Draw Rectangle
if event == cv2.EVENT_RBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,abs(ix-x),abs(iy-y))
elif event == cv2.EVENT_RBUTTONUP:
drawing = False
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,x,y)
roi.extend(rect)
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.setMouseCallback(title,onmouse)
print ("Right click and hold to draw a single rectangle ROI, beginning at the top left corner of the desired area. A blue box should appear. Hit esc to exit screen. Window can be resized by selecting borders.")
while True:
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.imshow(title,img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
print(roi)
return(roi)
def make_normal_mask(path_tis_msk, path_tumor_msk, path_save_location):
print('==> making normal mask...')
tis_msk = cv2.imread(path_tis_msk)
tumor_msk = cv2.imread(path_tumor_msk)
tumor_msk_bool = (tumor_msk == 255)
tis_msk_after = tis_msk.copy()
tis_msk_after[tumor_msk_bool] = 0
print('==> saving normal mask at' + path_save_location + ' ...')
cv2.imwrite(path_save_location, tis_msk_after)
### Display result
"""
cv2.namedWindow('tis_msk', cv2.WINDOW_NORMAL)
cv2.namedWindow('tis_msk_after', cv2.WINDOW_NORMAL)
cv2.namedWindow('tumor_msk', cv2.WINDOW_NORMAL)
cv2.resizeWindow('tis_msk', 512, 512)
cv2.resizeWindow('tis_msk_after', 512, 512)
cv2.resizeWindow('tumor_msk', 512, 512)
cv2.imshow('tis_msk', tis_msk)
cv2.imshow('tis_msk_after', tis_msk_after)
cv2.imshow('tumor_msk', tumor_msk)
cv2.waitKey()
cv2.destoryAllWindows()
"""
def showimages():
cv2.namedWindow('Source Image', cv2.WINDOW_AUTOSIZE)
cv2.namedWindow('Threshold Image', cv2.WINDOW_AUTOSIZE)
cv2.namedWindow('Binary Image', cv2.WINDOW_AUTOSIZE)
# cv2.namedWindow('Contour Image', cv2.WINDOW_NORMAL)
# cv2.namedWindow('noise_remove Image', cv2.WINDOW_NORMAL)
cv2.imshow("Source Image", src_img)
cv2.imshow("Binary Image", bin_img)
cv2.imshow("Threshold Image", final_thr)
# cv2.imshow("Contour Image", final_contr)
# cv2.imshow('noise_remove Image', noise_remove)
# plt.show()
def im_show(name, image, resize=1):
H, W = image.shape[0:2]
cv2.namedWindow(name, cv2.WINDOW_NORMAL)
cv2.imshow(name, image.astype(np.uint8))
cv2.resizeWindow(name, round(resize * W), round(resize * H))
def stream(quit, det):
"""
:param quit: Quit streaming
:param det: detection object
:return:
"""
global sav_frame
global sav_result
camera_src = None
if args.device == str(0): # jetson
camera_src = CameraSrc().get_cam_src()
else: # desktop
camera_src = 0
camera = cv2.VideoCapture(camera_src)
assert camera.isOpened()
if args.fullscreen:
cv2.namedWindow(args.device, cv2.WINDOW_NORMAL)
cv2.setWindowProperty(args.device,
cv2.WND_PROP_FULLSCREEN,
cv2.WINDOW_FULLSCREEN)
face_locs = None
alignedFace = None
while True:
_, frame = camera.read()
sav_frame = frame.copy()
# add frames to queue
frame_queue.put(sav_frame)
# display detection results
#face_locs = face_coordinates_queue.get()
#alignedFace = face_aligned_queue.get()
#if face_locs is not None:
# print(len(alignedFace), face_locs)
#det.display(frame=frame, face_locations=face_locs)
cv2.imshow(args.device, frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
quit.value = 1
break
camera.release()
cv2.destroyAllWindows()
# Main Process