def get_cropped(name, new=False): # If a new subject, call the Cloud Vision API if new: crop_image(name) polygon = None # Load bounding box with open(name + '.p', 'rb') as f: polygon = pickle.load(f) polygon = np.array([[p.x, p.y] for p in polygon]) # Load image and darken the image image = io.imread(name + '.jpg') image = exposure.adjust_gamma(image, gamma=1.5, gain=1) x = image.shape[1] y = image.shape[0] # Draw a rectangle to crop the image rect = mpatches.Rectangle((polygon[0][0] * x, polygon[0][1] * y), polygon[1][0] * x - polygon[0][0] * x, polygon[2][1] * y - polygon[0][1] * y, linewidth=1, edgecolor='r', facecolor='none') bbox = rect.get_bbox() cropped = image[int(bbox.y0):int(bbox.y1), int(bbox.x0):int(bbox.x1)] return cropped
def run_c3(image, training_path): """reads temperature for a single image""" #FOR CAMERA 3 ONLY info = check(image) valid = info[0] if valid != None: return valid width, height = info[1][0], info[1][1] exif_json = info[2] valid_heights = [2124] #pictype 3 heights valid_widths = [3776] #pictype 3 widths if width not in valid_widths or height not in valid_heights: return "Temp is: {0}".format(-9999) if not os.path.exists(os.getcwd() + '/temp/'): #if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/temp/') crop.crop_image(image, "temp/digits.jpg", 435, 0, 70, 30) #crops digits temperature = ocr_contour.recognize('temp/digits.jpg', training_path) #recognize digit os.remove(os.getcwd() + '/temp/digits.jpg') #clean up temp dir temp = '' for i in temperature: temp += i try: return int(temp) except: return "Temp is: {0}".format(-9999)
def run_c4(image, training_path): """reads temperature for a single image""" #FOR CAMERA 4 ONLY info = check(image) valid = info[0] if valid != None: return valid width, height = info[1][0], info[1][1] exif_json = info[2] valid_heights = [1512] #pictype 4 heights valid_widths = [2688] #pictype 4 widths if width not in valid_widths or height not in valid_heights: return int(-9999) if not os.path.exists(os.getcwd()+'/temp/'): #if temp folder doesnt exis, create one os.makedirs(os.getcwd()+'/temp/') crop.crop_image(image, "temp/digits.jpg", 825, 1445, 145, 70) temperature = ocr_contour.recognize('temp/digits.jpg', training_path, True) #recognize digits # im = cv2.imread('temp/digits.jpg') ##debugging # cv2.imshow('img', im) ##debugging # cv2.waitKey(0) ##debugging final = sorted(temperature, key = lambda x: x[1][0]) #sort from left to right os.remove(os.getcwd()+'/temp/digits.jpg') #clean up temp dir temp = '' for digit in final: temp += digit[0] try: return int(temp) except: return int(-9999)
def sortByEmotionMenu(self): crop.crop_image(self.pathImages) emotion_sort.sort_e(self.pathCroppedImages) PhotoGallery.gallery(self.pathSortedImages, 250, 200) self.updateGallery2() self.raise_frame(self.f3) videorender.render(self.pathSortedImages)
def run_c2(image, training_path): '''Reads temperature values from HC500/HC600 Hyperfire cameras Writes any found mismatches on task3/mismatches/ in a .txt file w/ a randomly generated filename''' info = check(image) valid = check(image)[0] width, height = info[1][0], info[1][1] valid_widths = [1920, 2048] # pictype 2 heights valid_heights = [1080, 1536] # pictype 2 widths if width not in valid_widths or height not in valid_heights: return int(-9999) if not os.path.exists(os.getcwd() + '/temp/'): # if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/temp/') if height == valid_heights[0] and width == valid_widths[0]: #1920x2040 crop.crop_image(image, "temp/digits.jpg", 1710, 0, 115, 30) # crops digits elif height == valid_heights[1] and width == valid_widths[1]: #2048x1536 crop.crop_image(image, "temp/digits.jpg", 1850, 0, 105, 30) temperature = ocr_contour.recognize(os.getcwd() + '/temp/digits.jpg', training_path) # recognize right digit # os.remove(os.getcwd()+'/temp/digits.jpg') #clean up temp dir ocr_temp = '' for digit in temperature: ocr_temp += digit if valid != None: exif_temp = int(valid) ocr_temp = int(ocr_temp) try: if ocr_temp != exif_temp: if not os.path.exists(os.getcwd() + '/mismatches/'): # if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/mismatches/') f = open("mismatches/{0}.jpg".format(id_generator()), "w") f.write("exif temp: {0}, ocr temp: {1}, filename: {2}".format(exif_temp,ocr_temp,image)) return int(ocr_temp) except: return int(-9999)
def sortByColorMenu(self): crop.crop_image(self.pathImages) colorfulness.sort_c(self.pathCroppedImages) PhotoGallery.gallery(self.pathSortedImages, 250, 200) self.updateGallery2() self.raise_frame(self.f3) videorender.render(self.pathSortedImages)
def run_c1(image, training_path): '''reads temperature of images in a directory. CAMERA 1 ONLY''' info = check(image) valid = info[0] width, height = info[1][0], info[1][1] exif_json = info[2] valid_heights = [2448] #pictype 3 heights valid_widths = [3264] #pictype 3 widths if width not in valid_widths or height not in valid_heights: return int(-9999) if valid != None: return valid if not os.path.exists(os.getcwd() + '/temp/'): # if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/temp/') crop.crop_image(image,'temp/digits.jpg', 790, 2355, 375, 70) crop.invert(os.getcwd() + '/temp/digits.jpg') info = ocr_contour.recognize(os.getcwd() + '/temp/digits.jpg', training_path, True) temp = [] for item in info: if item[0] == '45': x1,y1 = item[1][0], item[1][1] for item in info: if item[1][0] < x1: temp.append((item[0], item[1][0])) final = sorted(temp, key = lambda x: x[1]) temperature = '' for i in final: temperature += i[0] try: return int(temperature) except: return int(-9999)
def run_c3(image, training_path): """reads temperature for a single image""" #FOR CAMERA 3 ONLY info = check(image) valid = info[0] if valid != None: return valid width, height = info[1][0], info[1][1] exif_json = info[2] valid_heights = [2124] #pictype 3 heights valid_widths = [3776] #pictype 3 widths if width not in valid_widths or height not in valid_heights: return int(-9999) if not os.path.exists(os.getcwd()+'/temp/'): #if temp folder doesnt exis, create one os.makedirs(os.getcwd()+'/temp/') crop.crop_image(image, "temp/digits.jpg", 435, 0, 70, 30) #crops digits temperature = ocr_contour.recognize('temp/digits.jpg', training_path) #recognize digit os.remove(os.getcwd()+'/temp/digits.jpg') #clean up temp dir temp = '' for i in temperature: temp +=i try: return int(temp) except: return int(-9999)
def run_c1(image, training_path): '''reads temperature of images in a directory. CAMERA 1 ONLY''' info = check(image) valid = info[0] width, height = info[1][0], info[1][1] exif_json = info[2] valid_heights = [2448] #pictype 3 heights valid_widths = [3264] #pictype 3 widths if width not in valid_widths or height not in valid_heights: return "Temp is: {0}".format(-9999) if valid != None: return valid if not os.path.exists(os.getcwd() + '/temp/'): # if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/temp/') crop.crop_image(image, 'temp/digits.jpg', 790, 2355, 375, 70) crop.invert(os.getcwd() + '/temp/digits.jpg') info = ocr_contour.recognize(os.getcwd() + '/temp/digits.jpg', training_path, True) temp = [] for item in info: if item[0] == '45': x1, y1 = item[1][0], item[1][1] for item in info: if item[1][0] < x1: temp.append((item[0], item[1][0])) final = sorted(temp, key=lambda x: x[1]) temperature = '' for i in final: temperature += i[0] try: return int(temperature) except: return "Temp is: {0}".format(-9999)
def run_c4(image, training_path): """reads temperature for a single image""" #FOR CAMERA 4 ONLY info = check(image) valid = info[0] if valid != None: return valid width, height = info[1][0], info[1][1] exif_json = info[2] valid_heights = [1512] #pictype 4 heights valid_widths = [2688] #pictype 4 widths if width not in valid_widths or height not in valid_heights: return "Temp is: {0}".format(-9999) if not os.path.exists(os.getcwd() + '/temp/'): #if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/temp/') crop.crop_image(image, "temp/digits.jpg", 825, 1445, 145, 70) temperature = ocr_contour.recognize('temp/digits.jpg', training_path, True) #recognize digits # im = cv2.imread('temp/digits.jpg') ##debugging # cv2.imshow('img', im) ##debugging # cv2.waitKey(0) ##debugging final = sorted(temperature, key=lambda x: x[1][0]) #sort from left to right os.remove(os.getcwd() + '/temp/digits.jpg') #clean up temp dir temp = '' for digit in final: temp += digit[0] try: return int(temp) except: return "Temp is: {0}".format(-9999)
def main(args): if not os.path.exists(cropped_folder): os.mkdir(cropped_folder) if not os.path.exists(saliency_folder): os.mkdir(saliency_folder) if args.rgb_folder: rgb_pths = os.listdir(args.rgb_folder) for rgb_pth in rgb_pths: saliency(args.rgb_folder, rgb_pth) crop_image(args.rgb_folder, rgb_pth) #print(os.path.join(args.rgb_folder,rgb_pth)) else: saliency(None, args.rgb) crop_image(None, args.rgb)
def prepare_data(user_id: int): data = dict() source = user_videos[user_id]['source'] target = user_videos[user_id]['target'] audio_clip = AudioFileClip(target) data['audio'] = audio_clip if source.endswith('.jpg'): crop_image(source) else: # pass crop_video(source) try: source_reader = imageio.get_reader('crop_' + source) except FileNotFoundError: print("Didn't find cropped video") source_reader = imageio.get_reader(source) if source.endswith('.jpg'): data['source_media'] = resize(next(iter(source_reader)), (256, 256))[..., :3] data['photo'] = True else: data['source_media'] = read_video(source_reader) data['photo'] = False crop_video(target) try: target_reader = imageio.get_reader('crop_' + target) except FileNotFoundError: print("Didn't find cropped video") target_reader = imageio.get_reader(target) fps = target_reader.get_meta_data()['fps'] data['fps'] = fps data['target_media'] = read_video(target_reader) generator, kp_detector = load_checkpoints(config_path=CONFIG, checkpoint_path=CHECKPOINT, cpu=CPU) data['generator'] = generator data['kp_detector'] = kp_detector return data
def run_c2(image, training_path): '''Reads temperature values from HC500/HC600 Hyperfire cameras Writes any found mismatches on task3/mismatches/ in a .txt file w/ a randomly generated filename''' info = check(image) valid = check(image)[0] width, height = info[1][0], info[1][1] valid_widths = [1920, 2048] # pictype 2 heights valid_heights = [1080, 1536] # pictype 2 widths if width not in valid_widths or height not in valid_heights: return "Temp is: {0}".format(-9999) if not os.path.exists(os.getcwd() + '/temp/'): # if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/temp/') if height == valid_heights[0] and width == valid_widths[0]: #1920x2040 crop.crop_image(image, "temp/digits.jpg", 1710, 0, 115, 30) # crops digits elif height == valid_heights[1] and width == valid_widths[1]: #2048x1536 crop.crop_image(image, "temp/digits.jpg", 1850, 0, 105, 30) temperature = ocr_contour.recognize(os.getcwd() + '/temp/digits.jpg', training_path) # recognize right digit # os.remove(os.getcwd()+'/temp/digits.jpg') #clean up temp dir ocr_temp = '' for digit in temperature: ocr_temp += digit if valid != None: exif_temp = int(valid) ocr_temp = int(ocr_temp) try: if ocr_temp != exif_temp: if not os.path.exists(os.getcwd() + '/mismatches/' ): # if temp folder doesnt exis, create one os.makedirs(os.getcwd() + '/mismatches/') f = open("mismatches/{0}.jpg".format(id_generator()), "w") f.write("exif temp: {0}, ocr temp: {1}, filename: {2}".format( exif_temp, ocr_temp, image)) return int(ocr_temp) except: return "Temp is: {0}".format(-9999)
def main(args): if not os.path.exists(cropped_folder): os.mkdir(cropped_folder) if not os.path.exists(saliency_folder): os.mkdir(saliency_folder) if args.rgb_folder: rgb_pths = os.listdir(args.rgb_folder) count = 1 for rgb_pth in rgb_pths: print("IMAGE:", end=' ') print(count) count = count + 1 saliency(args.rgb_folder, rgb_pth) crop_image(args.rgb_folder, rgb_pth) print() #print(os.path.join(args.rgb_folder,rgb_pth)) else: saliency(None, args.rgb) crop_image(None, args.rgb)
def ajax_save_images(request): if request.user.is_authenticated(): img_crop_dict = copy.deepcopy(eval(request.POST['crop_dictionary'])) for file_key, file_val in request.FILES.items(): extra_details = ImageInfo.objects.filter(user=request.user, type='Profile') if len(extra_details) <= 0: file_val.name = str( request.user.id ) + '_' + file_key + '.' + file_val.name.split('.')[-1] extra_details = ImageInfo(user=request.user, type='Profile', photo=file_val) extra_details.save() else: extra_details = extra_details[0] counter = extra_details.photo.name.split('.')[0].split('_')[-1] try: counter = int(counter) + 1 except Exception: counter = 0 old_pic_name = extra_details.photo.name temp_list = old_pic_name.split('c_')[-1].split('.')[0].split( '_') tmp_var = temp_list[0] new_pic_name = tmp_var + '_' + str( counter) + '.' + old_pic_name.split('.')[-1] file_val.name = new_pic_name extra_details.photo = file_val extra_details.save() if img_crop_dict.has_key('upfile'): crop_dict = img_crop_dict['upfile'] crop_dict['image_name'] = extra_details.photo.name path = crop_image(crop_dict) extra_details.photo.name = path extra_details.save() path_image = settings.MEDIA_URL + path return HttpResponse(path_image) else: return HttpResponse('error in uploading file')
def grade_all(warped): total_grade = 0 try: gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] except: thresh = cv2.threshold(warped, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] if debug: show_image( thresh ) #------------------------------------------------------------------------------------------ first_part, second_part, third_part = crop_image(thresh) total_grade = grade_1(first_part) + grade_2(second_part) + grade_3( third_part) return total_grade
def ajax_save_images( request ): if request.user.is_authenticated(): img_crop_dict = copy.deepcopy( eval( request.POST['crop_dictionary'] ) ) for file_key, file_val in request.FILES.items(): extra_details = ImageInfo.objects.filter( user = request.user, type = 'Profile' ) if len( extra_details ) <= 0: file_val.name = str( request.user.id ) + '_' + file_key + '.' + file_val.name.split( '.' )[-1] extra_details = ImageInfo( user = request.user, type = 'Profile', photo = file_val ) extra_details.save() else: extra_details = extra_details[0] counter = extra_details.photo.name.split( '.' )[0].split( '_' )[-1] try: counter = int( counter ) + 1 except Exception: counter = 0 old_pic_name = extra_details.photo.name temp_list = old_pic_name.split( 'c_' )[-1].split( '.' )[0].split( '_' ) tmp_var = temp_list[0] new_pic_name = tmp_var + '_' + str( counter ) + '.' + old_pic_name.split( '.' )[-1] file_val.name = new_pic_name extra_details.photo = file_val extra_details.save() if img_crop_dict.has_key( 'upfile'): crop_dict = img_crop_dict['upfile'] crop_dict['image_name'] = extra_details.photo.name path = crop_image( crop_dict ) extra_details.photo.name = path extra_details.save() path_image = settings.MEDIA_URL + path return HttpResponse( path_image ) else: return HttpResponse( 'error in uploading file' )
def cropped_puzzle(self): # 원본 사진을 받아와서 오리기 self.cropped_puzzle = crop.crop_image(self.cellSize)
time.sleep(1) continue if int(data) == 1: print("GOt 1") elif int(data) == 2: print("GOt 2") elif int(data) == 3: print("GOt 3") elif int(data) == 4: print("GOt 4") else: continue print(data) image_path = "images/buttonrpi-yellow.jpg" end_result = {'description': ''} # camera.start_preview(alpha=200) camera.capture(image_path) # camera.stop_preview() crop_image(image_path, int(data)) image_analyze(end_result, image_path) print(end_result) if end_result["description"]: engine.say(end_result["description"]) engine.runAndWait() else: engine.say('Nothing to describe in the image.') socker.close()
parser.add_argument("--cpu", dest="cpu", action="store_true", help="cpu mode.") parser.add_argument("--from_image", dest="from_image", action="store_true") parser.set_defaults(relative=False) parser.set_defaults(adapt_scale=False) parser.set_defaults(from_image=False) opt = parser.parse_args() # opt.cpu = True if opt.from_image: crop.crop_image(opt.source_image) else: crop.crop_video(opt.source_image) crop.crop_video(opt.driving_video) try: source_reader = imageio.get_reader('crop_' + opt.source_image) except Exception as e: print(e) source_reader = imageio.get_reader(opt.source_image) if opt.from_image: source_photo = resize(next(iter(source_reader)), (256, 256))[..., :3] else: source_video = read_video(source_reader)
def zoom_image(image, percentage_height, percentage_width): height, width = image.shape[:2] newHeight = int(height + percentage_height/100 * height) newWidth = int(width + percentage_width/100 * width) zoomed = cv2.resize(img, dsize=(newHeight, newWidth)) return crop_image(zoomed, height, width)
print("GOt 2") elif int(data) == 3: print("GOt 3") elif int(data) == 4: print("GOt 4") else: continue print(data) image_path = sys.argv[1] if not os.path.exists(image_path): sys.exit() end_result = {'description': ''} # camera.start_preview(alpha=200) #camera.capture(image_path) # camera.stop_preview() filename, file_extension = os.path.splitext(image_path) cropped_path = 'images/cropped' + str(file_extension) crop_image(image_path, int(data), True) image_analyze(end_result, cropped_path) print(end_result) if end_result["description"]: engine.say(end_result["description"]) engine.runAndWait() else: engine.say('Nothing to describe in the image.') socket.close()
text = loader.preprocess(text) model = state.load_best_model() res = model.predict(np.array([text])) le_path = os.path.join(args['text_model'], 'label_encoder.pkl') le = loader.load_label_encoder(le_path) print("text label:") print(le.inverse_transform(res)) # image state = TrainingState(args['image_model']) loader = DataLoader('image') images = [] for i in crop_image(captcha): images.append(loader.preprocess(i)) model = state.load_best_model() res = model.predict(np.array(images)) le_path = os.path.join(args['image_model'], 'label_encoder.pkl') le = loader.load_label_encoder(le_path) print("image labels:") print(le.inverse_transform(res)) cv2.imshow('press any key to escape', captcha) cv2.waitKey(0)