def predict_image(): print(request.headers) print("Running") base64Image = base64.b64decode(request.data) pilImage = Image.open(io.BytesIO(base64Image)) print("Still Running") cv2Image = cv2.cvtColor(np.array(pilImage), cv2.COLOR_RGB2BGR) print("Extracting Logo!") extract = ExtractLogo() import src.utils as utils # Detecting page # from src.extraction.detectPage import detectPage # cv2Image = detectPage(cv2Image) # Instead of detecting page, directly reduce resolution and process cv2Image = utils.resize(cv2Image) utils.imshow(cv2Image) # No need of segmentation predictedLogoList, urlList = extract.extract(cv2Image, segment=False) # imFileLoc = "C:/Users/Abhishek Bansal/Desktop/img.jpg" # cv2.imwrite(imFileLoc, cv2Image) response = {} response["status"] = 200 response["answer"] = "Predicted logos are: " response["url"] = urlList[0][2:-1] print(urlList[0]) print(response["url"]) for logo in predictedLogoList: response["answer"] += logo print(json.dumps(response)) return json.dumps(response)
def transformaItem(square2, altura1, largura1, identificador, idx2): square2 = utils.resize(square2, width=largura1, height=altura1) im2, contours2, hierarchy = cv2.findContours(square2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(contours2, key=functionSort, reverse=True)[0] novaMat = np.zeros(square2.shape, dtype="uint8") cv2.drawContours(novaMat, [cnts], -1, 255, -1) utils.save('_img_{}.jpg'.format(idx2), novaMat, id=identificador) #recarrega a imagem do disco, suaviza e contorna path = utils.buildPath(identificador, path="_img_" + str(idx2) + ".jpg") imgGray = cv2.imread(path, cv2.COLOR_BGR2GRAY) #utils.save('debug_{}_antes.jpg'.format(idx2), imgGray, id=identificador) imgGray = cv2.medianBlur(imgGray, 5) utils.save('__{}_depois.jpg'.format(idx2), imgGray, id=identificador) retval, imgGray = cv2.threshold(imgGray, 2, 255, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) im2, contours, hierarchy = cv2.findContours(imgGray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts2 = contours[0] debugMat = np.zeros(imgGray.shape, dtype="uint8") cv2.drawContours(debugMat, [cnts2], -1, 255, -1) utils.save('debug_{}.jpg'.format(idx2), debugMat, id=identificador) return cnts2
def preprocess(self): # self.blurredImage = cv2.GaussianBlur(self.document, (5, 5), 0) self.removedEdgeImage = self.document[10:-10][10:-10] self.resizeImage = utils.resize(self.removedEdgeImage) if self.debug: utils.imshow(self.resizeImage) self.erodedImage = erodeImage.erode(self.resizeImage, self.debug) utils.imshow(self.erodedImage) print("Processed Image for Extraction!")
def pictures(cls, cid, is_resize, name): imgs = get_imgs(status=cls.novel.statusCode, aid=cls.novel.id, cid=cid, cookies=SelfUser.cookies) chapter_dir = cls.root_dir + "/" + name mkdir(chapter_dir) imgs_dir = chapter_dir + "/" + "插图" mkdir(imgs_dir) for i in imgs: with open(imgs_dir + "/" + str(imgs.index(i)) + ".jpg", "wb") as f: f.write( resize(request(i).content if is_resize else request(i).content))
def validaAssinaturaCnh(cnhColor, square1, identificador): cnhColor = utils.removeSombras(cnhColor) utils.save('cnh_semSombra.jpg', cnhColor, id=identificador) imgGray = cnhColor #cv2.cvtColor(cnhColor, cv2.IMREAD_GRAYSCALE) #imgGray = cv2.medianBlur(imgGray, 21) imgTh, contours, hierarchy = extraiContornos(imgGray, identificador) contours, resized = utils.ajustaEspacosContorno(contours, imgTh) utils.save('cnh_resized.jpg', resized, id=identificador) cnts = contours[0] novaMat = np.zeros(imgGray.shape, dtype = "uint8") cv2.drawContours(novaMat, [cnts], -1, 255, -1) xA, yA, wA, hA = cv2.boundingRect(cnts) square = novaMat[yA :yA + hA, xA : xA + wA ] utils.save('cnh_square.jpg', square, id=identificador) h, w = square1.shape resized = utils.resize(square, width=w, height=h) utils.save('_img_6.jpg', resized, id=identificador) path = utils.buildPath(identificador, path="_img_6.jpg") print("Novo path " + path) imgGray = cv2.imread(path, cv2.COLOR_BGR2GRAY) print(imgGray) #imgGray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY) retval, imgGray = cv2.threshold(imgGray, 2, 255, type = cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) imgGray, densidade = utils.removeContornosPqnosImg(imgGray) im2, contours, hierarchy = cv2.findContours(imgGray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #contours, resized = utils.ajustaEspacosContorno(contours, imgTh) cnts2 = contours[0] print("Total de contornos CNH ANTES: " + str(len(cnts))) print("Total de contornos CNH DEPOIS: " + str(len(cnts2))) return cnts2, resized
def processMatrix(self, path, file, permitAngles, permitScales): img = cv2.imread(join(path, file), 0) if self.__emptyImg is None: self.__createEmptyImg(img) for permitAngle in permitAngles: newImg = utils.rotate(img, permitAngle, color=(255, 255, 255)) cv2.imwrite(join(path, 'rot' + str(permitAngle) + file), newImg) for permitScale in permitScales: (h, w) = img.shape[:2] h = int(h * permitScale) newImg = utils.resize(img, h * 2, h) embedImg = self.__emptyImg.copy() embedImg[:newImg.shape[0], :newImg.shape[1]] = newImg cv2.imwrite(join(path, 'scale' + str(permitScale) + file), embedImg)
def inital_colorful_pic(file, sigma, kmeans): img = cv.imread(file) img = resize( img, WIN_SIZE, WIN_SIZE, ) img_gray = rgb2gray(img) # edge out_edge = canny(img_gray, sigma=float(sigma), mask=None).astype(np.uint8) out_edge[out_edge == 1] = 255 # color_domain # random_blur = 2 * np.random.randint(7, 18) + 1 out_blur = cv.medianBlur(img, 23) # K = np.random.randint(2, 6) out_blur = img_kmeans(out_blur, int(kmeans)) out_blur = cv.medianBlur(out_blur, np.random.randint(1, 4) * 2 - 1) return out_edge, out_blur
def __next__(self): x_data, y_data = [], [] while len(x_data) < self.batch_size: idx = np.random.randint(0, len(self.data)) x, y = self.data[idx] x = read_image(x) if x is None: self.data.pop(idx) continue x = crop(resize(x, base=self.size), target_shape=self.size) x = self.aug(x) x_data.append(x) y_data.append(y) x_data, y_data = np.array(x_data).astype('float32'), np.array(y_data) if self.transform: x_data = self.transform(x_data) y_data = to_categorical(y_data, self.classes) return x_data, y_data
for j in i["chapters"]: if j["name"] == "插图": print(f"下载{i['name']}插图中...") imgs_dir = chapter_dir + "/" + "插图" mkdir(imgs_dir) imgs = get_imgs(status=novel.statusCode, aid=novel.id, cid=j['cid'], cookies=cookies) for l in imgs: with open( imgs_dir + "/" + str(imgs.index(l)) + ".jpg", "wb") as f: print(f"保存第{str(imgs.index(l))}张插图") if isResize: f.write(resize( request(l, cookies).content)) else: f.write(to_jpg( request(l, cookies).content)) elif i["chapters"].index(j) == 0: c = request( f"http://dl3.wenku8.com/packtxt.php?aid={id}&vid={j['cid'] - 1}&charset=gbk", cookies) with open(chapter_dir + "/" + i["name"] + id + ".txt", "a") as f: print("保存中...") text = no_utf8_code(c.text) f.write(text) print("保存成功") print("下载完成!") except KeyboardInterrupt:
def _process_file(path, target_shape): img = read_image(path, prefix='test') if img is None: return img = resize(img, target_shape) return ten_crops(img, target_shape)
def screen(self): self._screen = self.env.env.ale.getScreenGrayscale(self._screen) a = resize(self._screen, (self.screen_height, self.screen_width)) return a
def screen(self): a = resize(rgb2gray(self._screen), (self.screen_height, self.screen_width)) return a
def _process_file(path, target_shape, prefix): img = read_image(path, prefix=prefix) if img is None: return img = resize(img, int(target_shape * 1.5)) return five_crops(img, target_shape)
# print("STEP 2: Find contours of paper") # cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2) # cv2.imshow("Outline", image) # cv2.waitKey(0) # cv2.destroyAllWindows() # apply the four point transform to obtain a top-down # view of the original image warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio) # convert the warped image to grayscale, then threshold it # to give it that 'black and white' paper effect # warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) # T = threshold_local(warped, 11, offset=10, method="gaussian") # warped = np.uint8(warped > T) * 255 # show the original and scanned images # print("STEP 3: Apply perspective transform") # cv2.imshow("Original", imutils.resize(orig, height=650)) # cv2.imshow("Scanned", imutils.resize(warped, height=650)) # cv2.waitKey(0) return warped if __name__ == "__main__": loc = "C:/Users/Abhishek Bansal/Desktop/Image Processing/Logo Identification/Logo2.jpg" image = cv2.imread(loc) utils.imshow(image) page = detectPage(image) page = utils.resize(page) utils.imshow(page)
def process_img(self, img): img = resize(img, base=int(self.size * 1.5)) return five_crops(img, size=self.size)