def __init__(self): """ 你的 APPID AK SK """ APP_ID = '16947698' API_KEY = 'fN9yStlTEv1zkWoMDMQU7YKT' SECRET_KEY = 'fqk4FfDRZp7fjk1ngcTeeaKtgWZxFh6H' self.gesture_client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) self.gesture_contrast = { "Ok": "1", "Thumb_up": "4", "Thumb_down": "5", "Insult": "2", "Six": "3", "Five": "6", "Fist": "7", "Honour": "8", } # 0指的是摄像头的编号。如果你电脑上有两个摄像头的话,访问第2个摄像头就可以传入1。 self.capture = cv2.VideoCapture(0) self.music_names = os.listdir('music') # 列表歌 self.music_source = [] # 音频播放路劲 self.current_music_no = 0 # 音乐 self.volume = 0.2 # 设置播放频道的音量
def bdcut(path): try: pic = Image.open(path) if pic.mode == "P": pic = pic.convert('RGB') # 有些图片有P通道,base编码后会出问题 (wf,hf) = pic.size BD_VIP='否' BD_AI_client = AipBodyAnalysis('替换appid','替换apikey','替换secrekey') with open(path, 'rb') as fp: x_nose = int(BD_AI_client.bodyAnalysis(fp.read())["person_info"][0]['body_parts']['nose']['x']) # 返回鼻子横坐标 if BD_VIP == '否': time.sleep(0.4) # 免费用户QPS=2 else: time.sleep( 1/int(1.1*BD_VIP) ) if x_nose + 1/3*hf > wf: # 判断鼻子在图整体的位置 x_left = wf-2/3*hf # 以右为边 elif x_nose - 1/3*hf < 0: x_left = 0 # 以左为边 else: x_left = x_nose-1/3*hf # 以鼻子为中线向两边扩展 fixed_pic = pic.crop((x_left,0,x_left+2/3*hf,hf)) fixed_pic.save(path.replace('fanart','poster'), quality=95) print('[+]百度AI裁剪操作成功') except: imagecut=1 print('[-] '+ path +' AI 分析失败,跳过 AI 直接裁剪。\n')
def gesture_recognition(): gesture_client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) frame = telloGetFrame(Drone) cv2.imshow('frame', frame) cv2.imwrite("{}.png".format(img_count), frame) image = get_file_content("{}.png".format(img_count)) gesture = gesture_client.gesture(image) #AipBodyAnalysis内部函数 print(gesture)
def __init__(self, configPath, configSection): keyInfo = fu.readConfig(configPath, configSection) self.appid = keyInfo['appid'] self.api_key = keyInfo['api_key'] self.secret_key = keyInfo['secret_key'] self.client = AipBodyAnalysis(self.appid, self.api_key, self.secret_key) self.filename = None self.picture = None self.picture_size = None self.picture_format = None
def analyse_people(self, filePath): client = AipBodyAnalysis(self.APP_ID, self.API_KEY, self.SECRET_KEY) """ 读取图片 """ with open(filePath, 'rb') as fp: data = client.bodyAttr(fp.read()) data = str(data) res = re.findall(r"'(.*?)': {'score': (0.\d+), 'name': '(.*?)'}", data, re.S) del res[0] for r in res: print("{:—<20}特征:{:—<15}精准度:{}".format(r[0],r[2], r[1])) """ 如果有可选参数 """
def body_seg(filename="./pic/test.jpg", savefilename="./pic/fore.jpg"): APP_ID = '19037846' API_KEY = 'pi8i47A8jGBH1VZDr8ioqgfC' SECRET_KEY = 'qwcqweVfjf9pX2fB6MykU15u6XszXko4' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) image = get_file(filename) options = {} options["type"] = "foreground" res = client.bodySeg(image, options) foreground = base64.b64decode(res["foreground"]) with open(savefilename, "wb") as f: f.write(foreground)
def pose_codelab(content, pose): #百度API通行证(获取方法见https://ai.baidu.com) APP_ID = '21219492' API_KEY = 'jC6Z4Fa9jTs6wtpUTkoyGVMV' SECRET_KEY = 'pbGBVFu41ZZRWHhtPEqUbGTaEekaKfqc' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) #输入ID和密钥建立连接 video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() #读取摄像头数据 #处理图片格式并发送给云端API frame_b = cv2.imencode(".jpg", frame)[1].tobytes() gesture_info = client.gesture(frame_b) #处理识别结果(API会将识别到的人脸和手势全部返回) if gesture_info['result']: result = gesture_info['result'] num = gesture_info['result_num'] for i in range(num): classname = result[i]['classname'] #识别的手势/人脸类别 #识别框坐标 left = result[i]['left'] top = result[i]['top'] width = result[i]['width'] height = result[i]['height'] #绘制识别框 cv2.rectangle(frame, (left, top), (left + width, top + height), (0, 0, 255), 2) if (classname == 'Face'): cv2.putText(frame, 'Face', (left, top + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1) else: cv2.putText(frame, '{}'.format(classname), (left, top + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1) pose.send_message_to_scratch(classname) #发送识别结果到scratch cv2.imshow('Video', frame) time.sleep(0.15) #防止QPS溢出 # Hit 'q' on the keyboard to quit! if cv2.waitKey(100) & 0xFF == ord('q'): break # time.sleep(5) # # Release handle to the webcam video_capture.release() cv2.destroyAllWindows()
def detection(self): clients = AipBodyAnalysis(self.APP_ID, self.API_KEY, self.SECRET_KEY) image = self.get_file_content('test.jpg') options = {} # """ 带参数调用人体检测与属性识别 """ res = clients.bodyAttr(image, options) data = res['person_info'][0]['attributes'] news = {} for k, v in data.items(): news[k] = v['name'] pprint(news)
def fanHuiTuPianGuanDianX_Y(url): #从百度AI获取到图片关键点返回值,参数为图片路径 """ 你的 APPID AK SK """ APP_ID = '22952436' API_KEY = 'a5UrzVfjQHyuK0GSCXk8QoQH' SECRET_KEY = '8wguEEmbNTnMfAOOOigMr1cM1SZXvq1c' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() image = get_file_content(url) return client.bodyAnalysis(image)
def bodypart(filename): # APP_ID = 'd90755ad2f2047dbabb12ad0adaa0b03' # API_KEY = 'b7b0f4d01f7f4aef9b5453f6558c23b1' # SECRET_KEY = '6ad666162ef24213b5bde7bdd904fcbe' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) # """ 读取图片 """ image = get_file_content(filename) # """ 调用人体关键点识别 """ para = client.bodyAnalysis(image) # print(para) # time.sleep(2) return para
def index(fileName): APP_ID = '' API_KEY = '' SECRET_KEY = '' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) image = get_file_content(fileName) """ 调用手势识别 """ res = client.gesture(image) if 'error_code' in res: print(res['error_msg']) try: classname = res['result'][0]['classname'] print(classname) return classname except Exception as err: print('手势识别失败')
def __init__(self): self.app_id = rospy.get_param("~app_id") self.api_key = rospy.get_param("~api_key") self.secret_key = rospy.get_param("~secret_key") self.client = AipBodyAnalysis(self.app_id, self.api_key, self.secret_key) self.bridge = CvBridge()
def __init__(self): APP_ID = '18721308' API_KEY = 'lNQGdBNazTPv8LpSP4x0GQlI' SECRET_KEY = 'nW8grONY777n4I2KvpOVuKGDNiY03omI' self.client_face = AipFace(APP_ID, API_KEY, SECRET_KEY) self.client_body = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) self.image_type = "BASE64" filepath = "/Pictures/image.jpg" msg = reception_image() self.guest = Guest() # self.name = None # self.age = None # self.image = None # self.gender = None # self.drink = None self.options_body = {} self.options_body["type"] = "gender,upper_color,upper_wear_fg" self.options_face = {} self.options_face["face_field"] = "age,gender" self.options_face["max_face_num"] = 3 self.options_face["face_type"] = "LIVE" #发布器 self.roi_pub = rospy.Publisher('/image/roi',RegionOfInterest,queue_size=1) self.objpos_pub = rospy.Publisher('/image/object_position2d',String,queue_size=1) self.control_pub = rospy.Pubscriber("/control", reception, queue_size=1) self.speech_pub = rospy.Pubscriber('/speech/check_door',reception_image,self.find_people) #订阅器 self.control_sub = rospy.Subscriber("/control", reception, self.controlCallback) self.ROI = RegionOfInterest()
class BaiduAIP(object): def __init__(self): self.client = AipBodyAnalysis(cfg.APP_ID, cfg.API_KEY, cfg.SECRET_KEY) def bodyAnalysis(self, img_jpg): etval, buffer = cv2.imencode('.jpg', img_jpg) result = self.client.bodyAnalysis(buffer) # 内部把buffer转换为base64了 return result
def AutoCutout(path): APP_ID = '19815134' API_KEY = 'i7yBb3Fx3e4ZMILo8nHsrZQT' SECRET_KEY = 'wuEXaPYbz1RXlAdDYYRj49tlPoNZdqfW' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) imgfile = path ori_img = cv2.imread(imgfile) height, width, _ = ori_img.shape with open(imgfile, 'rb') as fp: img_info = fp.read() seg_res = client.bodySeg(img_info) labelmap = base64.b64decode(seg_res['labelmap']) nparr = np.fromstring(labelmap, np.uint8) labelimg = cv2.imdecode(nparr, 1) labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST) new_img = np.where(labelimg == 1, 255, labelimg) result = cv2.bitwise_and(ori_img, new_img) cv2.imwrite(path, result)
def Seg_img(jpg_path, crop_path, save_path): ''' 调用API 分割人像图片 :param jpg_path: 原图像 :param crop_path: 裁剪之后图像 :param save_path: 生成 mask 存放路径 :return: ''' # 通过百度控制台申请得到的 AK 和 SK; APP_ID = "23633750" API_KEY = 'uqnHjMZfChbDHvPqWgjeZHCR' SECRET_KEY = 'KIKTgD5Dh0EGyqn74Zqq8wHWB39uKaS3' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) # 文件夹 jpg_file = os.listdir(jpg_path) # 要保存的文件夹 for i in jpg_file: open_file = os.path.join(jpg_path, i) save_file = os.path.join(save_path, i) if not os.path.exists(save_file): #文件不存在时,进行下步操作 img = cv2.imread(open_file) # 获取图像尺寸 height, width, _ = img.shape if crop_path: # 若Crop_path 不为 None,则不进行裁剪 crop_file = os.path.join(crop_path, i) img = img[100:-1, 300:-400] #图片太大,对图像进行裁剪 cv2.imwrite(crop_file, img) image = get_file_content(crop_file) else: image = get_file_content(open_file) res = client.bodySeg(image) #调用百度API 对人像进行分割 labelmap = base64.b64decode(res['labelmap']) labelimg = np.frombuffer(labelmap, np.uint8) # 转化为np数组 0-255 labelimg = cv2.imdecode(labelimg, 1) labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST) img_new = np.where(labelimg == 1, 255, labelimg) # 将 1 转化为 255 cv2.imwrite(save_file, img_new) print(save_file, 'save successfully')
def parseimage(self, image): filename = 'images/gesture.png' cv2.imwrite(filename, image) myimage = self.get_file_content(filename) client = AipBodyAnalysis(self.APP_ID, self.API_KEY, self.SECRET_KEY) result = client.gesture(myimage) print(result) if result["result_num"] > 0: data = result['result'] print(data[0]["classname"]) if data[0]['classname'] == ('Heart_single' or 'Heart_1' or 'Heart_2' or 'Heart_3'): self.robotpi_movement.move_left() if data[0]['classname'] == 'Fist': self.robotpi_movement.wave_hands() if data[0]['classname'] == 'Rock': self.robotpi_movement.play_sound(2, 16) else: print("暂无结果") self.robotpi_movement.play_sound(2, 4)
def __init__(self): self.time = time.time() APP_ID = '18889374' API_KEY = 'pUNweNaSK4rWz57vGs9KpuW1' SECRET_KEY = 'ru5LqWM0lrcVYBh9cjd32fy951nagqcA' self.image_type = "BASE64" self.client_face = AipFace(APP_ID, API_KEY, SECRET_KEY) self.client_body = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) self.client_body.setConnectionTimeoutInMillis(2000) self.client_body.setSocketTimeoutInMillis(2000) self.client_face.setConnectionTimeoutInMillis(2000) self.client_face.setSocketTimeoutInMillis(2000) self.bridge = CvBridge() self.ispub = False ##############人类数据 self.filepath = "/home/qian/catkin_ws/src/fare_src/kamerider_image/kamerider_image_api/imgfile/" ##############跟踪数据 self.roi = None self.depth_array = None self.target_pos = Pose() ##############话题名称 # 接收器与发布器 self.check_gender = rospy.get_param('~check_gender', 'False') if (type(self.check_gender) == type('text')): self.check_gender = False ##############发布器 self.img_pub = rospy.Publisher("/image/test", Image, queue_size=1) self.roi_pub = rospy.Publisher("roi", RegionOfInterest, queue_size=1) self.img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.imgCallback, queue_size=1) self.word_pub = rospy.Publisher("/xfwords", String, queue_size=1) self.face_pub = rospy.Publisher("/start_recognize_faces", String, queue_size=1) print("============================================================")
def __init__(self): self.qe = queue self.q = self.qe.Queue(maxsize=5) """ 你的人流量统计 APPID AK SK """ self.APP_ID = '16193424' self.API_KEY = 'eqZCDofIR6FXWaMHr5bszls6' self.SECRET_KEY = 'CIlH54Ro1HvpZwQR4nQbetQEcnPqWbUQ' self.aipBodyAnalysis = AipBodyAnalysis(self.APP_ID, self.API_KEY, self.SECRET_KEY) # self.aipFace = AipFace(Aself.PP_ID, self.API_KEY, self.SECRET_KEY) self.cap = cv2.VideoCapture("http://49.90.255.4:10001/8.ts")
class tylt_AipBodyAnalysis: def __init__(self): self.APP_ID = '14372361' self.API_KEY = 'rwIh36pOcyqV8S9rQ6BBQlxh' self.SERECT_KEY = 'NiHoVNuAwK1RoBRypCKo6OPQrdopWU2Y' self.client = AipBodyAnalysis(self.APP_ID, self.API_KEY, self.SERECT_KEY) def body_attr(self, image): return self.client.bodyAttr(image) @staticmethod def dealwith_body_attr_result(person_info_list): """ 处理人体属性信息并返回 :param person_info_list: 人体属性信息列表 :return: """ response_list = [] for person in person_info_list: attributes = person['attributes'] location = { 'left': person['location']['left'], 'top': person['location']['top'], 'width': person['location']['width'], 'height': person['location']['height'], } person_info_dict = { 'upper_wear_fg': attributes['upper_wear_fg']['name'], 'cellphone': attributes['cellphone']['name'], 'lower_cut': attributes['lower_cut']['name'], 'umbrella': attributes['umbrella']['name'], 'orientation': attributes['orientation']['name'], 'headwear': attributes['headwear']['name'], 'gender': attributes['gender']['name'], 'age': attributes['age']['name'], 'upper_cut': attributes['upper_cut']['name'], 'glasses': attributes['glasses']['name'], 'lower_color': attributes['lower_color']['name'], 'bag': attributes['bag']['name'], 'upper_wear_texture': attributes['upper_wear_texture']['name'], 'smoke': attributes['smoke']['name'], 'vehicle': attributes['vehicle']['name'], 'lower_wear': attributes['lower_wear']['name'], 'carrying_item': attributes['carrying_item']['name'], 'upper_wear': attributes['upper_wear']['name'], 'upper_color': attributes['upper_color']['name'], 'occlusion': attributes['occlusion']['name'], 'location': location, } response_list.append(person_info_dict) return response_list
def face_center(filename, model): app_id = config.getInstance().conf.get("face", "appid") api_key = config.getInstance().conf.get("face", "key") app_secret = config.getInstance().conf.get("face", "secret") client = AipBodyAnalysis(app_id, api_key, app_secret) with open(filename, 'rb') as fp: img = fp.read() result = client.bodyAnalysis(img) if 'error_code' in result: raise ValueError(result['error_msg']) print('[+]Found person ' + str(result['person_num'])) # 中心点取鼻子x坐标 maxRight = 0 maxTop = 0 for person_info in result["person_info"]: x = int(person_info['body_parts']['nose']['x']) top = int(person_info['location']['top']) if x > maxRight: maxRight = x maxTop = top return maxRight, maxTop
def init_body_detection(): # baidu clond AI detection project https://console.bce.baidu.com app_id = "18480308" api_key = "r1ddkBzIGucxEwCkRArbrZGn" secret_key = "7ZCAHQaVWvuKP2MCKRxbdgiL3eMbGbhy" client = AipBodyAnalysis(app_id, api_key, secret_key) client.setConnectionTimeoutInMillis(4000) client.setSocketTimeoutInMillis(7000) options = {"type": "gender,age"} def detective(image): try: r = client.bodyAttr(image, options) if r["person_num"] == 0: Log.logger.info("image contain no person") return [], "no_body" for person in r['person_info']: if person['attributes']['gender']['name'] == "男性": Log.logger.info("male has been detected, discard") return [], "male" if person['attributes']['gender']['score'] < 0.6: Log.logger.info("not that much like a girl discard") return [], "neutral" if person['attributes']['age']['name'] == "幼儿": Log.logger.info("children has been detected, discard") return [], "children" except Exception as e: Log.logger.warning("image can't be processed {}".format(e)) return [], "error" return [r], "girl" return detective
def __init__(self): APP_ID = '18721308' API_KEY = 'lNQGdBNazTPv8LpSP4x0GQlI' SECRET_KEY = 'nW8grONY777n4I2KvpOVuKGDNiY03omI' self.client_face = AipFace(APP_ID, API_KEY, SECRET_KEY) self.client_body = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) self.image_type = "BASE64" msg = reception_image() self.guest = Guest() # self.name = None # self.age = None # self.image = None # self.gender = None # self.drink = None self.options_body = {} self.options_body["type"] = "gender,upper_color,upper_wear_fg" self.options_face = {} self.options_face["face_field"] = "age,gender" self.options_face["max_face_num"] = 3 self.options_face["face_type"] = "LIVE" #ros params self.sub_image_raw_topic_name = None self.sub_destination_topic_name = None self.pub_gender_recognition_topic_name = None self.pub_object_position2d = None # self.depth_img = np.array((480,640)) self.get_params() #发布器 self.objpos_pub = rospy.Publisher('/image/object_position2d', String, queue_size=1) #订阅器 self.control_sub = rospy.Subscriber("/control", reception, self.controlCallback) self.speech_sub = rospy.Subscriber('/speech/check_door', String, self.find_people)
def gestureRecog(self): APP_ID = '16534881' API_KEY = 'DSG6hUBgBVt61Ms1XXnYuEPm' SECRET_KEY = 'W4nkl6xYmOnRjntg53fDMuxQXvqemNI0' a = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) cap=cv2.VideoCapture(0) while 1: ret,image=cap.read() cv2.imshow("capture", image) if cv2.waitKey(100)&0xff==ord("q"): cv2.imwrite("test.jpg", image) break cap.release() cv2.destroyAllWindows() filePath = "test.jpg" options = {} options["top_num"] = 5 result=a.gesture(self.get_file_content(filePath),options) print(result) k=result["result"][0]["classname"] if k=="Insult": self.port_reset() if k=="ILY": self.Slider_3.setValue(500) time.sleep(0.5) self.Slider_3.setValue(1500) else: return
def __init__(self): self.time = time.time() APP_ID = '18889374' API_KEY = 'pUNweNaSK4rWz57vGs9KpuW1' SECRET_KEY = 'ru5LqWM0lrcVYBh9cjd32fy951nagqcA' self.imageType = "BASE64" self.client_face = AipFace(APP_ID, API_KEY, SECRET_KEY) self.client_body = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) self.bridge = CvBridge() ##############人类数据 self.filepath = "/home/dell/img/" self.option_face = {} self.option_body = {} self.option_face["face_field"] = "age,gender,glasses,race" self.option_face["max_face_num"] = 1 self.option_body["type"] = "upper_wear,upper_color" ##############跟踪数据 self.roi = None ##############话题名称 # 接收器与发布器 self.sub_image_name = rospy.get_param('~image_raw_topic_name', '/usb_cam/image_raw') # 发布器 self.pub_pos_name = rospy.get_param('~object_view_topic_name', 'roi') self.pub_img_name = rospy.get_param('~image_test_topic_name', '/image/test') self.pub_fet_name = rospy.get_param('~feature_topic_name', '/image/feature') ##############发布器 self.img_pub = rospy.Publisher(self.pub_img_name, Image) self.roi_pub = rospy.Publisher(self.pub_pos_name, RegionOfInterest) self.fet_pub = rospy.Publisher(self.pub_fet_name, Description) self.img_sub = rospy.Subscriber(self.sub_image_name, Image, self.imgCallback) print("============================================================")
class BaiDuAPI(object): #特殊 构造函数 初始化函数 def __init__(self, filePath): target = configparser.ConfigParser() target.read(filePath, encoding='utf-8-sig') self.client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) """ 读取图片 """ def get_file_content(self, photoPath): with open(photoPath, 'rb') as fp: return fp.read() """ 主函数 """ def file_main(self, photoPath): #转码 #base64_data = base64.b64encode(photoPath) # add by me f = open(photoPath, 'rb') img = base64.b64encode(f.read()) #img = self.get_file_content('{}'.format(photoPath)) """ 调用人体关键点识别 """ #此处只能对一个人进行关键点识别 #也就是说一个图片如果有好多人的话,只能标出一个人的关节特征 #此处可以做修改,即进行把一张图所有人的关节特征都表达出来 #------ print(self.client.bodyAnalysis(img)) result = self.client.bodyAnalysis(img)['person_info'][0]['body_parts'] jo = joint.Joint(result) jo.xunhun(photoPath) print(result)
def cut_picture(src): # 在百度云中申请,每天各接口有 500 次调用限制. APP_ID = '16628525' API_KEY = '5ioBzjijPln33f7mPzyProbc' SECRET_KEY = 'FR4URtsr2Q77r6RvNyld4swls1Eik5Pu' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) # 读取待分割人像图片 imgfile = src ori_img = cv2.imread(imgfile) height, width, _ = ori_img.shape with open(imgfile, 'rb') as fp: img_info = fp.read() # print("img_info:", img_info) seg_res = client.bodySeg(img_info) labelmap = base64.b64decode(seg_res['labelmap']) nparr = np.fromstring(labelmap, np.uint8) labelimg = cv2.imdecode(nparr, 1) labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST) new_img = np.where(labelimg == 1, 255, labelimg) # maskfile = imgfile.replace('.jpg', '_mask.png') maskfile_dir = './static/image/cut/' + \ imgfile.split('/')[-1].split('.')[0]+'_mask.png' cv2.imwrite(maskfile_dir, new_img) # res_imgfile = imgfile.replace('.jpg', '_res.jpg') result = cv2.bitwise_and(ori_img, new_img) # 保存最终分割出的人像图片到原始图片所在目录 result_path = './static/image/cut/' + \ imgfile.split('/')[-1].split('.')[0]+'_res.jpg' cv2.imwrite(result_path, result)
def bodyseg(filename): # APP_ID = 'd90755ad2f2047dbabb12ad0adaa0b03' # API_KEY = 'b7b0f4d01f7f4aef9b5453f6558c23b1' # SECRET_KEY = '6ad666162ef24213b5bde7bdd904fcbe' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) # """ 读取图片 """ image = get_file_content(filename) res = client.bodySeg(image) print(res) labelmap = base64.b64decode(res['labelmap']) # time.sleep(2) nparr_labelmap = np.fromstring(labelmap, np.uint8) labelmapimg = cv2.imdecode(nparr_labelmap, 1) print(labelmapimg.shape) im_new_labelmapimg = np.where(labelmapimg == 1, 255, labelmapimg) # print(im_new_labelmapimg.shape) # img=cv2.cvtColor(im_new_labelmapimg, cv2.COLOR_BGR2GRAY) # return img.astype('uint8') # cv2.imwrite('outline.png',im_new_labelmapimg) return im_new_labelmapimg
def picscoket(self,a,q): APP_ID = ····· API_KEY = ···· SECRET_KEY = ····· client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) while True: if q.qsize() >= 1: pic = q.get() image = self.get_file_content(pic) client.bodyNum(image) options = {} options["area"] = "0,0,100,100,200,200" options["show"] = "false" client.bodyNum(image, options) num = client.bodyNum(image, options) testnum = json.dumps(num) testnum2 = json.loads(testnum) testnum3 = testnum2['person_num'] db = pymysql.connect('localhost', 'root', 'root', 'camera') cursor = db.cursor() ye = now = datetime.datetime.now() ye = ye.strftime('%y') mo = now = datetime.datetime.now() mo = mo.strftime('%m') da = now = datetime.datetime.now() da = da.strftime('%d') sql = "INSERT INTO num(year ,person_num,month,day) VALUES ( '%s', '%s','%s','%s')" % (ye, testnum3, mo, da) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 如果发生错误则回滚 db.rollback() # 关闭数据库连接 db.close() print(testnum3) else: print('为空') time.sleep(5)
from aip import AipBodyAnalysis import json import cv2 as cv APP_ID ='11589803' API_KEY ='K2WOMV1pCyI1IXIbvawDDRhu' SECRET_KEY = 'VxQRvsETnYHsEZsWi9lGrLhhV5Q1slaX' client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY) #读取照片 def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() #绘制方块 def print_div(a,j): img=cv.imread(a) for i in range(j['person_num']): cv.rectangle(img,(int(j['person_info'][i]['location']['left']),int(j['person_info'][i]['location']['top'])), (int(j['person_info'][i]['location']['left']+j['person_info'][i]['location']['width']),int(j['person_info'][i]['location']['top']+j['person_info'][i]['location']['height'])), (0,255,0),3) cv.namedWindow("Image",cv.WINDOW_NORMAL) cv.imshow("Image",img) cv.waitKey(0) cv.destroyAllWindows() #选择功能 def select_power(): i=input(''' 选择需要的功能 1.人体关键点识别