def detect_online(self): key_value = self.rfile.read(int( self.headers["content-length"])).decode() name = key_value.split("=")[0] url = key_value.split("=")[1] if name == "online_image_url": try: url = urllib.parse.unquote(url) req = urllib.request.Request(url, headers=UA) data = urllib.request.urlopen(req, timeout=5).read() data = io.BytesIO(data) # detect image = Image.open(data) detect_results = vision.detect_image(image, isWeb=True) self.send_json(detect_results) print("detect online image API -> " + url) except: print(traceback.print_exc()) self.send_error(500, "detect failed for this image!") else: print("post parameter invalid!") self.send_error(500, "parameter invalid!")
def detect_online(self): '''detect online image API''' key_value = self.rfile.read(int( self.headers["content-length"])).decode() name = key_value.split("=")[0] url = key_value.split("=")[1] # only handle the right parameter if name == "online_image_url": try: # download the image from url url = urllib.parse.unquote(url) req = urllib.request.Request(url, headers=UA) data = urllib.request.urlopen(req, timeout=5).read() data = io.BytesIO(data) # detect with vision module image = Image.open(data) detect_results = vision.detect_image(image) # send the json result to client self.send_json(detect_results) print("detect online image API -> " + url) except: print(traceback.print_exc()) self.send_error(500, "detect failed for this image!") else: print("post parameter invalid!") self.send_error(500, "parameter invalid!")
def detect_local(self): '''detect local image API''' try: data = self.rfile.read(int(self.headers["content-length"])) data = io.BytesIO(data) # need parse the base post info, and pass to cgi.FieldStorage, which can help us to parse the whole post body(with file data) content_type = self.headers["content-type"] index = content_type.find( "boundary=" ) # make sure multipart/form-data, we need image data from post body if index < 0: self.send_error(500, "invalid parameters!") else: fs = cgi.FieldStorage(fp=data, environ={ "REQUEST_METHOD": "POST", "CONTENT_TYPE": content_type, "CONTENT_LENGTH": self.headers["content-length"] }, headers=self.headers, keep_blank_values=True) image_data = io.BytesIO( fs["local_image"].value ) # get the file data, 'local_image' is the element's name in html # detect with vision module image = Image.open(image_data) detect_results = vision.detect_image(image) # send the json result to client self.send_json(detect_results) print("detect local image API -> ") except: print(traceback.print_exc()) self.send_error(500, "detect failed for this image!")