def __call__(self, opt): exps = sorted(os.listdir('./runs')) assert len(exps), f'Experiments not exists, please train model first' q = "\n".join([f'[{i:>2}] {x}' for i, x in enumerate(exps)]) ipt = input( f'Existing experiments:\n{q}\nPlease select which model to evaluate\n' f'(0 for model0, 0,1,2 for model0,1,2): ') ipt = '0' if ipt == '' else ipt indexes = [int(x) for x in ipt.split(',')] if ',' in ipt else [int(ipt)] for idx in indexes: print('\n') exp = exps[idx] opt.weights = f'./runs/{exp}/weights/best.pt' roi = int(opt.use_roi) ssvm = int(opt.use_ssvm) tp = f'{Path(opt.source).parent}/{exp}_sz{opt.img_size}_ROI{roi}_SSVM{ssvm}{opt.fog}' # target path flag = 0 # 0: detect and evaluate, 1: direct evaluate if os.path.exists(tp): ipt = input(f'Output_path: {tp} exists, \nevaluate without detect [YES/no]: ') if ipt in ['Yes', 'y', 'Y', 'yes', '']: flag = 1 elif ipt in ['No', 'N', 'n']: flag = 0 else: raise NotImplementedError(f'input error: {ipt}') if flag == 0: opt.output = tp print(f'opt: {opt}') dp = post.DmPost(opt) detect.run(opt, dp) ret = self.gcm.analyse(thresh=0.5, v5_out=tp, pn_dir=Path(opt.source).parent) time, ret = self.read_time_and_fps(tp=tp)
def main(): if len(sys.argv) >= 2 and sys.argv[1] == '-h': exit_usage(0) if len(sys.argv) != 4: exit_usage(1) net = sys.argv[1] weight_file = sys.argv[2] img_dir = sys.argv[3] detect.init(net, weight_file) files = sorted(os.listdir(img_dir)) run_time = 0 img_num = 0 for f in files: if f.split('.')[-1] != 'jpg': continue file_path = img_dir + '/' + f img = cv2.imread(file_path, 1) time_start = time.time() bbox = detect.run(img, img.shape[0], img.shape[1]) time_end = time.time() run_time = run_time + time_end - time_start img_num = img_num + 1 print("[%.6f, %.6f, %.6f, %.6f]" % (bbox[0], bbox[1], bbox[2], bbox[3])) draw_bbox(img, bbox) detect.cleanup() print("total image number: %d" % img_num) print("frames per second of detection: %.6f" % (img_num / run_time))
def index(): print('Request-form',list(request.form.keys()),file=sys.stderr) print('Request-form-name',request.form['name'],file=sys.stderr) # print('Request-form-image',request.form['image'],file=sys.stderr) image_name = request.form['name'] image_string = request.form['image'] #image_bytes = bytes(image_string,'utf-8') #image_decoded = base64.decodestring(image_string) image = Image.open(BytesIO(base64.b64decode(image_string))) rotated_image = image.rotate(270,expand=True) input_array = np.array(rotated_image) input_array = np.expand_dims(input_array,axis=0) result_array = detect.run(input_array) result_image = Image.fromarray(result_array) #print('rotated_image.shape = ',input_array.shape) #rotated_image.save('default.jpg',format='JPEG') #convert image back to string.. buffered = BytesIO() result_image.save(buffered, format="JPEG") final_img_str = base64.b64encode(buffered.getvalue()) # print('Request-files:',request.files,file=sys.stderr) # print('Requestfiletype:',type(request.files),file=sys.stderr) # data = request.files.to_dict() # print('data',data,file=sys.stderr) # #to-do Input file validation... (ensure input file is valid jpg or png) # file = data['upload'] # print('File name:',file.filename,file=sys.stderr) # file_path = os.path.join("Images",file.filename) # file.save(file_path) # print('File saved with name:',file.filename,file=sys.stderr) #Deserialize the image.. # with open(image_name,'wb') as image_file: # image_file.write(image) response = final_img_str return response
def yolov5_server_callback(self, request, response): self.get_logger().info('Incoming request successful') bridge = CvBridge() cv_image = bridge.imgmsg_to_cv2(request.img, desired_encoding='bgr8') # Check if there is a faster way to send an image to yolov5 cv2.imwrite(SRC, cv_image) obj_roi_arr = detect.run(weights=WEIGHTS, source=SRC, conf_thres=CONF, nosave=True) print("result: {}".format(obj_roi_arr)) response.obj_roi_arr = obj_roi_arr print("sending response ... ") return response
roll = math.degrees(roll) if get_num(point_dict, 60, 1) > get_num(point_dict, 72, 1): roll = -roll print( f"Image: {img_name.split('/')[-1]} has the following angles:\n Pitch: {pitch:.2f}; Yaw: {yaw:.2f}; Roll: {roll:.2f}\n" ) plot_euler_angles(pitch, yaw, roll, img_name) if __name__ == '__main__': model = load_angle_model('./model.pth') parser = argparse.ArgumentParser() parser.add_argument('--source', type=str, default='./data/samples', help='source') # file or directory parser.add_argument('--cropped', type=str, default='./data/cropped', help='cropped images') # file or directory opt = parser.parse_args() detect.run(source=opt.source) run_inference(model=model, opt=opt) if os.path.exists('./data/cropped'): shutil.rmtree('./data/cropped') # delete output folder os.makedirs('./data/cropped') # make new output folders if os.path.exists('./data/web' ): # delete images downloaded from web if there are any shutil.rmtree('./data/web') # delete output folder
if name == "person": name = "Planetarium" resp = {} # [x, y] top_left, top_right = item['topLeft'] bottom_left, bottom_right = item['bottomRight'] return_string = 'There is {} in your {}.' if top_left < half_width and bottom_left < half_width: response += return_string.format(name, "left side") elif top_right > half_width and bottom_right > half_width: response += return_string.format(name, "right side") else: response + return_string.format(name, "center") if name == "Planetarium": description = get_planeteriums_events() response += " " + description return response if __name__ == '__main__': try: server_port = int(sys.argv[1]) except Exception: server_port = 8080 run() if not os.path.isdir('saved_images'): os.mkdir('saved_images') app.run(debug=True, host="0.0.0.0")
from PIL import Image from flask import Flask, request, send_file, jsonify, render_template, url_for from flask_cors import CORS from werkzeug.utils import secure_filename import detect UPLOAD_FOLDER = '/upload' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) CORS(app) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER run = detect.run() net = run.load_model(model_name='u2net') logging.basicConfig(level=logging.INFO) # @app.route("/", methods=["GET"]) # def hello(): # return 'Hello guys' @app.route("/", methods=['GET', 'POST']) def upload_file(): return render_template('upload.html') @app.route("/remove", methods=["GET", "POST"])
def run(): url = "http://60.214.100.134:10001/artemis-web/debug/" path_unhanded = 'unhanded/100121/' path_handed = 'ai-dispose/100121/' dict = { "appKey": "23189490", "appSecret": "k0CzWXJUOBH0yMlq9D31", "contentType": "application/x-www-form-urlencoded;charset=UTF-8", "headers": "{}", "httpMethod": "GET", "mock": "false", "parameter": "{}", "path": "/api/mss/v1/hls/37046803001310516439", "query": "{}" } i = 0 req1 = requests.post(url, dict) jsession1 = json.loads(req1.text) nurl = jsession1['data'].replace("10.141.71.28:83", "60.214.100.134:10001") #print(nurl) mysql = pymysql.connect(host='127.0.0.1', user='******', password='******', port='3306', db='Xztest') cursor = mysql.cursor() while True: # start_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:00', '%Y-%m-%d%H:%M') # end_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:30', '%Y-%m-%d%H:%M') # now_time = datetime.datetime.now() # if start_time<now_time<end_time: try: consiquent_fail = 0 # 连续失败帧数 max_consiquent_fail = 50 # 最大连续失败帧数 while True: cap = cv2.VideoCapture(nurl) ret, frame = cap.read() # 取流失败 if not ret: consiquent_fail += 1 if consiquent_fail >= max_consiquent_fail: break # 失败过量则重连 cap # 取流成功 else: for j in range(3): cur_time = int(round(time.time() * 1000)) standart_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) save_path = path_unhanded + cur_time + ".jpg" cv2.imwrite(save_path, frame[:, :, ::-1]) res = detect.run(weights='weights/best.pt', source=save_path, project='ai-dispose', name='100121') # if len(res): # sql = 'insert into t_ai_img values (%s,%s,%s,%s)' # param = ('ai-dipose/100121/'+cur_time+'.jpg','煤堆未覆盖',standart_time,cur_time) # cursor.execute(sql,param) # mysql.commit() for img in res: cur_time = int(round(time.time() * 1000)) standart_time = time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime()) size = os.path.getsize('ai-dispose/100121/' + img) / 1024 sql = 'insert into t_ai_img(video_no, label, img_url, create_time, video_url, img_no, size, update_time) values (%s,%s,%s,%s,%s,%s,%s,%s)' param = ('37046803001310516439', '裸漏煤堆/物料堆场扬尘识别', '1111', standart_time, '2222', cur_time, size, standart_time) cursor.execute(sql, param) mysql.commit() i = i + 1 time.sleep(60) time.sleep(1800) break except cv2.error as err: print(err) continue mysql.close() cursor.close()
except cv2.error as err: print(err) continue mysql.close() cursor.close() mysql = pymysql.connect(host='127.0.0.1', user='******', password='******', port=3306, db='Xztest') cursor = mysql.cursor() res = detect.run(weights='weights/best.pt', source='unhanded', project='ai-dispose', name='100121') print(res) # if len(res): # sql = 'insert into t_ai_img values (%s,%s,%s,%s)' # param = ('ai-dipose/100121/'+cur_time+'.jpg','煤堆未覆盖',standart_time,cur_time) # cursor.execute(sql,param) # mysql.commit() for img in res: cur_time = int(round(time.time() * 1000)) standart_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) size = os.path.getsize('ai-dispose/100121/' + img) / 1024 sql = 'insert into t_ai_img(video_no, label, img_url, create_time, video_url, img_no, size, update_time) values (%s,%s,%s,%s,%s,%s,%s,%s)' param = ('37046803001310516439', '裸漏煤堆/物料堆场扬尘识别', '1111', standart_time,
# load_video(opt.video_path) load_video(video_path) for file in os.scandir('output/overwatch/'): os.remove(file.path) print("-- Complete get frames") print( "-----------------------------------------------------------------------------------" ) # run YOLO print("\n-- Write name of weights file: weights/", end='') file = input() file_path = f"weights/{file}" detect.run(file_path) os.system(f"python detect.py --weights_path {file_path}") print( "-----------------------------------------------------------------------------------" ) # get features print("\n-- Getting features ...") get_features.cal_dist("output", 960.0, 540.0) print("-- Complete get features") print( "-----------------------------------------------------------------------------------" ) # classify print("\n-- Classifying ...")