我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.INTER_CUBIC。
def loadImgs(imgsfolder, rows, cols): myfiles = glob.glob(imgsfolder+'*.jpg', 0) nPics = len(myfiles) X = np.zeros((nPics, rows, cols), dtype = 'uint8') i = 0; imgNames = [] for filepath in myfiles: sd = filepath.rfind('/'); ed = filepath.find('.'); filename = filepath[int(sd+1):int(ed)] imgNames.append(filename) temp = cv2.imread(filepath, 0) if temp == None: continue elif temp.size < 1000: continue elif temp.shape == [rows, cols, 1]: X[i,:,:] = temp else: X[i,:,:] = cv2.resize(temp,(cols, rows), interpolation = cv2.INTER_CUBIC) i += 1 return X, imgNames
def lineRecognizer(path): ''' :param path ???????? :returns lines_data ?????????resize_pic ?????? ''' img = cv2.imread(path,cv2.IMREAD_GRAYSCALE) resize_pic=img #resize_pic=cv2.resize(img,(640,480),interpolation=cv2.INTER_CUBIC) edges = cv2.Canny(resize_pic,50,150) lines_data = cv2.HoughLines(edges,1,np.pi/180,150) return lines_data,resize_pic
def filter_image(image, canny1=10, canny2=10, show=False): # compute the ratio of the old height to the new height, and resize it image = imutils.resize(image, height=scale_factor, interpolation=cv2.INTER_CUBIC) # convert the image to grayscale, blur it, and find edges in the image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, canny1, canny2) # show the image(s) if show: cv2.imshow("Edged", edged) cv2.waitKey(0) cv2.destroyAllWindows() return edged
def loadLogoSet(path, rows,cols,test_data_rate=0.15): random.seed(612) _, imgID = readItems('data.txt') y, _ = modelDict(path) nPics = len(y) faceassset = np.zeros((nPics,rows,cols), dtype = np.uint8) ### gray images noImg = [] for i in range(nPics): temp = cv2.imread(path +'logo/'+imgID[i]+'.jpg', 0) if temp == None: noImg.append(i) elif temp.size < 1000: noImg.append(i) else: temp = cv2.resize(temp,(cols, rows), interpolation = cv2.INTER_CUBIC) faceassset[i,:,:] = temp y = np.delete(y, noImg,0); faceassset = np.delete(faceassset, noImg, 0) nPics = len(y) index = random.sample(np.arange(nPics), int(nPics*test_data_rate)) x_test = faceassset[index,:,:]; x_train = np.delete(faceassset, index, 0) y_test = y[index]; y_train = np.delete(y, index, 0) return (x_train, y_train), (x_test, y_test)
def get_batch_idx(self, idx): hh = self.inp_height ww = self.inp_width x = np.zeros([len(idx), hh, ww, 3], dtype='float32') orig_height = [] orig_width = [] ids = [] for kk, ii in enumerate(idx): fname = self.ids[ii] ids.append('{:06}'.format(ii)) x_ = cv2.imread(fname).astype('float32') / 255 x[kk] = cv2.resize( x_, (self.inp_width, self.inp_height), interpolation=cv2.INTER_CUBIC) orig_height.append(x_.shape[0]) orig_width.append(x_.shape[1]) pass return { 'x': x, 'orig_height': np.array(orig_height), 'orig_width': np.array(orig_width), 'id': ids }
def format_img(img, C): img_min_side = float(C.im_size) (height,width,_) = img.shape if width <= height: f = img_min_side/width new_height = int(f * height) new_width = int(img_min_side) else: f = img_min_side/height new_width = int(f * width) new_height = int(img_min_side) fx = width/float(new_width) fy = height/float(new_height) img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC) img = img[:, :, (2, 1, 0)] img = img.astype(np.float32) img[:, :, 0] -= C.img_channel_mean[0] img[:, :, 1] -= C.img_channel_mean[1] img[:, :, 2] -= C.img_channel_mean[2] img /= C.img_scaling_factor img = np.transpose(img, (2, 0, 1)) img = np.expand_dims(img, axis=0) return img, fx, fy
def preprocess_vgg19_mil(Image): if len(Image.shape) == 2: Image = Image[:, :, np.newaxis] Image = np.concatenate((Image, Image, Image), axis=2) mean = np.array([[[103.939, 116.779, 123.68]]]); base_image_size = 565; Image = cv2.resize(np.transpose(Image, axes=(1, 2, 0)), (base_image_size, base_image_size), interpolation=cv2.INTER_CUBIC) Image_orig = Image.astype(np.float32, copy=True) Image_orig -= mean im = Image_orig #im, gr, grr = upsample_image(Image_orig, base_image_size) # im = cv2.resize(Image_orig, (base_image_size, base_image_size), interpolation=cv2.INTER_CUBIC) im = np.transpose(im, axes=(2, 0, 1)) im = im[np.newaxis, :, :, :] return im
def update_vis(self): ims = self.opt_engine.get_images(self.frame_id) if ims is not None: self.ims = ims if self.ims is None: return ims_show = [] n_imgs = self.ims.shape[0] for n in range(n_imgs): # im = ims[n] im_s = cv2.resize(self.ims[n], (self.width, self.width), interpolation=cv2.INTER_CUBIC) if n == self.select_id and self.topK > 1: t = 3 # thickness cv2.rectangle(im_s, (t, t), (self.width - t, self.width - t), (0, 255, 0), t) im_s = im_s[np.newaxis, ...] ims_show.append(im_s) if ims_show: ims_show = np.concatenate(ims_show, axis=0) g_tmp = utils.grid_vis(ims_show, self.grid_size[1], self.grid_size[0]) # (nh, nw) self.vis_results = g_tmp.copy() self.update()
def predict(url): global model # Read image image = io.imread(url) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) image = cv2.resize(image, (500, 500), interpolation=cv2.INTER_CUBIC) # Use otsu to mask gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) mask = cv2.medianBlur(mask, 5) features = describe(image, mask) state = le.inverse_transform(model.predict([features]))[0] return {'type': state}
def preprocess(img): results_0 = detector.detect_face(img) if len(results_0) != 0: result_0 = max(results_0, key=lambda r: r['area']) else: result_0 = None result_1 = detector_dlib.getLargestFaceBoundingBox(img) if result_0 is not None and result_1 is not None: if result_1.area() * 0.6 > result_0['area']: crop_img = detector_dlib.prepocessImg(img, result_1) else: crop_img = crop_rotate(img, result_0['left_eye'], result_0['right_eye'], result_0['width']) elif result_0 is not None and result_1 is None: crop_img = crop_rotate(img, result_0['left_eye'], result_0['right_eye'], result_0['width']) elif result_0 is None and result_1 is not None: crop_img = detector_dlib.prepocessImg(img, result_1) else: crop_img = img[70:210, 65:185, :] crop_img = cv2.resize(crop_img, (96, 112), interpolation=cv2.INTER_CUBIC) return crop_img
def addEmoji(img,faces,emoji): for x,y,w,h in faces: # Resize emoji to desired width and height dim = max(w,h) em = cv.resize(emoji, (dim,dim), interpolation = cv.INTER_CUBIC) # Get boolean for transparency trans = em.copy() trans[em == 0] = 1 trans[em != 0] = 0 # Delete all pixels in image where emoji is nonzero img[y:y+h,x:x+w,:] *= trans # Add emoji on those pixels img[y:y+h,x:x+w,:] += em return img # Add emojis to image at specified points and sizes # Inputs: img is ndarrays of WxHx3 # emojis is a list of WxHx3 emoji arrays # faces is a list of (x,y,w,h) tuples for each face to be replaced # Labels is a list of integer labels for each emotion
def resize_addset(source_folder, target_folder, dsize, pattern=FILE_PATTERN): print('Resizing additional set...') if not os.path.exists(target_folder): os.makedirs(target_folder) for clazz in ClassNames: if clazz not in os.listdir(target_folder): os.makedirs(os.path.join(target_folder, clazz)) total_images = glob.glob(os.path.join(source_folder, clazz, pattern)) total = len(total_images) for i, source in enumerate(total_images): filename = ntpath.basename(source) target = os.path.join(target_folder, clazz, filename.replace('.jpg', '.png')) try: img = cv2.imread(source) img_resized = cv2.resize(img, dsize, interpolation=cv2.INTER_CUBIC) cv2.imwrite(target, img_resized) except: print('-------------------> error in: {}'.format(source)) if i % 20 == 0: print("Resized {}/{} images".format(i, total))
def cropCircle(img, resize=None): if resize: if (img.shape[0] > img.shape[1]): tile_size = (int(img.shape[1] * resize / img.shape[0]), resize) else: tile_size = (resize, int(img.shape[0] * resize / img.shape[1])) img = cv2.resize(img, dsize=tile_size, interpolation=cv2.INTER_CUBIC) else: tile_size = img.shape gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY); _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY) _, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) main_contour = sorted(contours, key=cv2.contourArea, reverse=True)[0] ff = np.zeros((gray.shape[0], gray.shape[1]), 'uint8') cv2.drawContours(ff, main_contour, -1, 1, 15) ff_mask = np.zeros((gray.shape[0] + 2, gray.shape[1] + 2), 'uint8') cv2.floodFill(ff, ff_mask, (int(gray.shape[1] / 2), int(gray.shape[0] / 2)), 1) rect = maxRect(ff) rectangle = [min(rect[0], rect[2]), max(rect[0], rect[2]), min(rect[1], rect[3]), max(rect[1], rect[3])] img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]] cv2.rectangle(ff, (min(rect[1], rect[3]), min(rect[0], rect[2])), (max(rect[1], rect[3]), max(rect[0], rect[2])), 3, 2) return [img_crop, rectangle, tile_size]
def _heatmap(x, y, confidences, activations, threshold=0.2): channel, height, width = x.shape heatmaps = [] max_activation = 0 for activation, confidence in six.moves.zip(activations, confidences): heatmap = np.zeros((height, width)) activation = confidence * cv2.resize(activation, (width, height), interpolation=cv2.INTER_CUBIC) heatmap = heatmap + activation heatmaps.append(heatmap) max_activation = np.max([max_activation, np.max(heatmap)]) for heatmap in heatmaps: heatmap[np.where(heatmap <= max_activation * threshold)] = 0.0 total_heatmap = np.zeros((height, width)) for heatmap in heatmaps: total_heatmap = total_heatmap + heatmap return (x, y, heatmaps, total_heatmap)
def drive(self): ''' Get the image infront and ''' latest_image = self.cozmo.world.latest_image screen = np.array(latest_image.raw_image) screen = cv2.resize(screen, (200, 120), interpolation=cv2.INTER_CUBIC) cv2.imshow('window1', screen) cv2.imwrite("./a.jpg", screen) image = screen.astype(dtype=np.float32)/255.0 key_code = self.model.y_out.eval(session=self.sess, feed_dict={self.model.x: [image], self.model.keep_prob_fc1:1.0, self.model.keep_prob_fc2:1.0, self.model.keep_prob_fc3:1.0, self.model.keep_prob_fc4:1.0}) print ("after judgeing, key_code is", key_code ) self.go_driving(key_code)
def get_mnist_data(is_train, image_size, batchsize): ds = MNISTCh('train' if is_train else 'test', shuffle=True) if is_train: augs = [ imgaug.RandomApplyAug(imgaug.RandomResize((0.8, 1.2), (0.8, 1.2)), 0.3), imgaug.RandomApplyAug(imgaug.RotationAndCropValid(15), 0.5), imgaug.RandomApplyAug(imgaug.SaltPepperNoise(white_prob=0.01, black_prob=0.01), 0.25), imgaug.Resize((224, 224), cv2.INTER_AREA) ] ds = AugmentImageComponent(ds, augs) ds = PrefetchData(ds, 128*10, multiprocessing.cpu_count()) ds = BatchData(ds, batchsize) ds = PrefetchData(ds, 256, 4) else: # no augmentation, only resizing augs = [ imgaug.Resize((image_size, image_size), cv2.INTER_CUBIC), ] ds = AugmentImageComponent(ds, augs) ds = BatchData(ds, batchsize) ds = PrefetchData(ds, 20, 2) return ds
def _remove_line_(self, img): # ?????? newimg = np.zeros(img.shape, np.uint8) newimg = cv2.resize(newimg, (img.shape[1], img.shape[0] - top - bottom), interpolation=cv2.INTER_CUBIC) for i in range(7, 20): for j in range(img.shape[1]): newimg[i - top, j] = img[i, j] # ??????? line = [] for i in range(newimg.shape[0]): hasline = False if newimg[i, 0] < 100: line.append(i) hasline = True for j in range(newimg.shape[1]): if hasline: newimg[i, j] = 0 else: if newimg[i, j] < 100: newimg[i, j] = 255 else: newimg[i, j] = 0 # top 7 left 7-10 bottom 10 return newimg
def imresize(img, scale): """Depending on if we scale the image up or down, we use an interpolation technique as per OpenCV recommendation. :param img: 3D numpy array of image. :param scale: float to scale image by in both axes. """ if scale > 1.0: # use cubic interpolation for upscale. img = cv2.resize(img, None, interpolation=cv2.INTER_CUBIC, fx=scale, fy=scale) elif scale < 1.0: # area relation sampling for downscale. img = cv2.resize(img, None, interpolation=cv2.INTER_AREA, fx=scale, fy=scale) return img
def load_image(im_id: str, rgb_only=False, align=True) -> np.ndarray: im_rgb = tiff.imread('./three_band/{}.tif'.format(im_id)).transpose([1, 2, 0]) if rgb_only: return im_rgb im_p = np.expand_dims(tiff.imread('sixteen_band/{}_P.tif'.format(im_id)), 2) im_m = tiff.imread('sixteen_band/{}_M.tif'.format(im_id)).transpose([1, 2, 0]) im_a = tiff.imread('sixteen_band/{}_A.tif'.format(im_id)).transpose([1, 2, 0]) w, h = im_rgb.shape[:2] if align: key = lambda x: '{}_{}'.format(im_id, x) im_p, _ = _aligned(im_rgb, im_p, key=key('p')) im_m, aligned = _aligned(im_rgb, im_m, im_m[:, :, :3], key=key('m')) im_ref = im_m[:, :, -1] if aligned else im_rgb[:, :, 0] im_a, _ = _aligned(im_ref, im_a, im_a[:, :, 0], key=key('a')) if im_p.shape != im_rgb.shape[:2]: im_p = cv2.resize(im_p, (h, w), interpolation=cv2.INTER_CUBIC) im_p = np.expand_dims(im_p, 2) im_m = cv2.resize(im_m, (h, w), interpolation=cv2.INTER_CUBIC) im_a = cv2.resize(im_a, (h, w), interpolation=cv2.INTER_CUBIC) return np.concatenate([im_rgb, im_p, im_m, im_a], axis=2)
def _aligned(im_ref, im, im_to_align=None, key=None): w, h = im.shape[:2] im_ref = cv2.resize(im_ref, (h, w), interpolation=cv2.INTER_CUBIC) im_ref = _preprocess_for_alignment(im_ref) if im_to_align is None: im_to_align = im im_to_align = _preprocess_for_alignment(im_to_align) assert im_ref.shape[:2] == im_to_align.shape[:2] try: cc, warp_matrix = _get_alignment(im_ref, im_to_align, key) except cv2.error as e: logger.info('Error getting alignment: {}'.format(e)) return im, False else: im = cv2.warpAffine(im, warp_matrix, (h, w), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP) im[im == 0] = np.mean(im) return im, True
def preprocessing(input_image,input_height,input_width): resized_image = cv2.resize(input_image,(input_height, input_width), interpolation = cv2.INTER_CUBIC) image_data = np.array(resized_image, dtype='f') # Normalization [0,255] -> [0,1] image_data /= 255. # BGR -> RGB? The results do not change much # copied_image = image_data #image_data[:,:,2] = copied_image[:,:,0] #image_data[:,:,0] = copied_image[:,:,2] image_array = np.expand_dims(image_data, 0) # Add batch dimension return image_array
def preprocessing(input_img_path,input_height,input_width): input_image = cv2.imread(input_img_path) # Resize the image and convert to array of float32 resized_image = cv2.resize(input_image,(input_height, input_width), interpolation = cv2.INTER_CUBIC) image_data = np.array(resized_image, dtype='f') # Normalization [0,255] -> [0,1] image_data /= 255. # BGR -> RGB? The results do not change much # copied_image = image_data #image_data[:,:,2] = copied_image[:,:,0] #image_data[:,:,0] = copied_image[:,:,2] # Add the dimension relative to the batch size needed for the input placeholder "x" image_array = np.expand_dims(image_data, 0) # Add batch dimension return image_array
def ridgeComp(img,theta, blockSize,w=3,h=9,alpha=100,beta=1): resize=5 N,M=np.shape(img) imgout=np.zeros_like(img) imgresizeize=cv2.resizeize(img,None,fx=resize,fy=resize,interpolation = cv2.INTER_CUBIC) mask=np.ones((w,h))*beta mask[(w-1)/2]=np.ones((1,h))*alpha ww=np.arange(-(w-1)/2,(w-1)/2+1) hh=np.arange(-(h-1)/2,(h-1)/2+1) hh,ww=np.meshgrid(hh,ww) for i in xrange((h-1)/2,N-(h-1)/2): block_i=i/blockSize for j in xrange((h-1)/2,M-(h-1)/2): block_j=j/blockSize thetaHere=theta[block_i,block_j] ii=np.round((i+ww*np.cos(thetaHere)-hh*np.sin(thetaHere))*resize).astype(np.int32) jj=np.round((j+ww*np.sin(thetaHere)+hh*np.cos(thetaHere))*resize).astype(np.int32) imgout[i,j]=np.sum(imgresizeize[ii,jj]*mask)/(((w-1)*beta+alpha)*h)
def binarize2(img,theta,blockSize,h=9): resize=5 N,M=np.shape(img) imgout=np.zeros_like(img) imgresizeize=cv2.resizeize(img,None,fx=resize,fy=resize,interpolation = cv2.INTER_CUBIC) blockMean=blockproc(img,np.mean,(blockSize,blockSize),True) hh=np.arange(-(h-1)/2,(h-1)/2+1) for i in xrange((h-1)/2,N-(h-1)/2): block_i=i/blockSize for j in xrange((h-1)/2,M-(h-1)/2): block_j=j/blockSize thetaHere=theta[block_i,block_j] ii=np.round((i-hh*np.sin(thetaHere))*resize).astype(np.int32) jj=np.round((j+hh*np.cos(thetaHere))*resize).astype(np.int32) imgout[i,j]=255 if (np.mean(imgresizeize[ii,jj])>blockMean[block_i,block_j]) else 0 return imgout
def ridgeComp(img,theta,blockSize,boxSize,h=11): resize=8 N,M=np.shape(img) imgout=img.copy() imgResize=cv2.resize(img,None,fx=resize,fy=resize,interpolation = cv2.INTER_CUBIC) hh=np.arange(-(h-1)/2,(h-1)/2+1) for i in xrange(10,N-10): block_i = (i-blockSize/2)/boxSize if block_i>=theta.shape[0]: break for j in xrange(10,M-10): block_j = (j-blockSize/2)/boxSize if block_j>=theta.shape[1]: break theta0=theta[block_i,block_j] ii=np.round((i-hh*np.sin(theta0))*resize).astype(np.int32) jj=np.round((j+hh*np.cos(theta0))*resize).astype(np.int32) imgout[i,j]=np.mean(imgResize[ii,jj]) return imgout
def _resize(img, size, interpolation): img = img.transpose((1, 2, 0)) if interpolation == PIL.Image.NEAREST: cv_interpolation = cv2.INTER_NEAREST elif interpolation == PIL.Image.BILINEAR: cv_interpolation = cv2.INTER_LINEAR elif interpolation == PIL.Image.BICUBIC: cv_interpolation = cv2.INTER_CUBIC elif interpolation == PIL.Image.LANCZOS: cv_interpolation = cv2.INTER_LANCZOS4 H, W = size img = cv2.resize(img, dsize=(W, H), interpolation=cv_interpolation) # If input is a grayscale image, cv2 returns a two-dimentional array. if len(img.shape) == 2: img = img[:, :, np.newaxis] return img.transpose((2, 0, 1))
def adapt_images_and_densities(images, gts, slice_w = slice_w, slice_h = slice_h): out_images = [] out_gts = [] for i, img in enumerate(images): img_h, img_w, _ = img.shape n_slices_h = int(round(img_h/slice_h)) n_slices_w = int(round(img_w/slice_w)) new_img_h = float(n_slices_h *slice_h) new_img_w = float(n_slices_w*slice_w) fx = new_img_w / img_w fy = new_img_h/img_h out_images.append(cv2.resize(img, None, fx = fx, fy = fy, interpolation = cv2.INTER_CUBIC)) assert out_images[-1].shape[0]%slice_h == 0 and out_images[-1].shape[1]%slice_w == 0 if gts is not None: out_gts.append(density_resize(gts[i], fx, fy)) return (out_images, out_gts)
def resize(images, size=(100, 100)): """ Function to resize the number of pixels in an image. To achieve a standarized pixel number accros different images, it is desirable to make every picture of the same pixel size. By using an OpenCV method we increase or reduce the number of pixels accordingly. """ images_norm = [] for image in images: is_color = len(image.shape) == 3 if is_color: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # using different OpenCV method if enlarging or shrinking if image.shape < size: image_norm = cv2.resize(image, size, interpolation=cv2.INTER_AREA) else: image_norm = cv2.resize(image, size, interpolation=cv2.INTER_CUBIC) images_norm.append(image_norm) return images_norm
def load_frames(clips_info): img_size = (cfg.IMG_RAW_H, cfg.IMG_RAW_W) N = len(clips_info) data = np.zeros( (N, cfg.TIME_S) + img_size + (3,), dtype=np.uint8) for clip_count, clip_info in enumerate(clips_info): video_path, start_frame = clip_info clip = np.zeros((cfg.TIME_S, 3) + img_size) for frame_count in range(cfg.TIME_S): filename = cfg.IMAGE_FORMAT.format(start_frame) img = cv2.imread(os.path.join(video_path, filename)) # in case image was not resized at extraction time if img.shape[1:] != img_size: img = cv2.resize( img, img_size[::-1], interpolation=cv2.INTER_CUBIC) img = img.transpose([2, 0, 1]) clip[frame_count] = img[np.newaxis, ...] start_frame += 1 clip = clip.transpose([0, 2, 3, 1]) data[clip_count] = clip[np.newaxis, ...] return data
def logoDetect(img,imgo): '''???????????????''' imglogo=imgo.copy() img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) img=cv2.resize(img,(2*img.shape[1],2*img.shape[0]),interpolation=cv2.INTER_CUBIC) #img=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,-3) ret,img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) #img=cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize = 9) img=cv2.Canny(img,100,200) element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) img = cv2.dilate(img, element2,iterations = 1) img = cv2.erode(img, element1, iterations = 3) img = cv2.dilate(img, element2,iterations = 3) #???? im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) tema=0 result=[] for con in contours: x,y,w,h=cv2.boundingRect(con) area=w*h ratio=max(w/h,h/w) if area>300 and area<20000 and ratio<2: if area>tema: tema=area result=[x,y,w,h] ratio2=ratio #?????????????????,?????????? logo2_X=[int(result[0]/2+plate[0]-3),int(result[0]/2+plate[0]+result[2]/2+3)] logo2_Y=[int(result[1]/2+max(0,plate[1]-plate[3]*3.0)-3),int(result[1]/2+max(0,plate[1]-plate[3]*3.0)+result[3]/2)+3] cv2.rectangle(img,(result[0],result[1]),(result[0]+result[2],result[1]+result[3]),(255,0,0),2) cv2.rectangle(imgo,(logo2_X[0],logo2_Y[0]),(logo2_X[1],logo2_Y[1]),(0,0,255),2) print tema,ratio2,result logo2=imglogo[logo2_Y[0]:logo2_Y[1],logo2_X[0]:logo2_X[1]] cv2.imwrite('./logo2.jpg',logo2) return img
def img_pre_treatment(file_path): im = cv2.imread(file_path) resize_pic=cv2.resize(im,(640,480),interpolation=cv2.INTER_CUBIC) resize_pic = cv2.GaussianBlur(resize_pic,(5,5),0) cv2.imwrite('static/InterceptedIMG/resize.jpg',resize_pic) kernel = np.ones((3,3),np.uint8) resize_pic = cv2.erode(resize_pic,kernel,iterations = 3) resize_pic = cv2.dilate(resize_pic,kernel,iterations = 3) cv2.imshow('image',resize_pic) k = cv2.waitKey(0) & 0xFF if k == 27: cv2.destroyAllWindows() gray = cv2.cvtColor(resize_pic,cv2.COLOR_BGR2GRAY) ret, binary = cv2.threshold(gray,90,255,cv2.THRESH_BINARY) cv2.imshow('image',binary) k = cv2.waitKey(0) & 0xFF if k == 27: cv2.destroyAllWindows() return resize_pic,binary
def rotate_image(img_src, angle,scale ,crop=True): img_src,size_dest= pad_image(img_src,scale) size = tuple(np.array([img_src.shape[1], img_src.shape[0]])) org_h=size[1] org_w=size[0] src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2) org_angle =np.arctan(float(org_h)/org_w) dest_h = size_dest[0] dest_w = size_dest[1] center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] * 0.5])) dsize= (dest_w,dest_h) rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale) img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC) if crop: x,y,w,h = cv2.boundingRect(img_rot[:,:,3]) return img_rot[y:y+h, x:x+w,:] else: return img_rot
def rotate_image(img_src, angle,scale ): img_src,size_dest= pad_image(img_src,scale) size = tuple(np.array([img_src.shape[1], img_src.shape[0]])) org_h=size[1] org_w=size[0] src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2) org_angle =np.arctan(float(org_h)/org_w) dest_h = size_dest[0] dest_w = size_dest[1] center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] * 0.5])) dsize= (dest_w,dest_h) rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale) img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC) x,y,w,h = cv2.boundingRect(img_rot[:,:,3]) return img_rot[y:y+h, x:x+w,:]
def match_all(self, pattern, threshold=None): pattern = self.pattern_open(pattern) search_img = pattern.image pattern_scale = self._cal_scale(pattern) if pattern_scale != 1.0: search_img = cv2.resize(search_img, (0, 0), fx=pattern_scale, fy=pattern_scale, interpolation=cv2.INTER_CUBIC) threshold = threshold or pattern.threshold or self.image_match_threshold screen = self.region_screenshot() screen = imutils.from_pillow(screen) points = ac.find_all_template(screen, search_img, threshold=threshold, maxcnt=10) return points
def load_image(path): # load image nImgs = len(path) rImg = np.zeros([nImgs,224,224,3]) for i in range(nImgs): img = cv2.imread(path[i]) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = cv2.resize(img,(224,224),interpolation = cv2.INTER_CUBIC) #skimage.transform.resize(crop_img, (224, 224)) rImg[i] = resized_img return rImg # returns the top1 string
def get_frame_prediction(self): ret, frame = self.cap.read() # if we get a frame if not ret: raise IOError('No image found!') frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_CUBIC) frame = frame.astype('uint8') return frame # Normalizes inputs so we don't have to worry about weird # characters e.g. \r\n
def preprocessing_imgs(train_imgs, reduced_size = None): # resizing if reduced_size is not None: train_imgs_p = np.ndarray((train_imgs.shape[0], train_imgs.shape[1]) + reduced_size, dtype=np.float32) for i in range(train_imgs.shape[0]): train_imgs_p[i, 0] = cv2.resize(train_imgs[i, 0], (reduced_size[1], reduced_size[0]), interpolation=cv2.INTER_CUBIC) # INVERSE ORDER! cols,rows else: train_imgs_p = train_imgs.astype(np.float32) # ZMUV normalization m = np.mean(train_imgs_p).astype(np.float32) train_imgs_p -= m st = np.std(train_imgs_p).astype(np.float32) train_imgs_p /= st return train_imgs_p,m,st
def vilization_and_show(): model = model_EES16() model.load_weights("EES_check.h5") IMG_NAME = "comic.bmp" INPUT_NAME = "input.jpg" img = cv2.imread(IMG_NAME) shape = img.shape img = cv2.resize(img, (shape[1] / 2, shape[0] / 2), cv2.INTER_CUBIC) cv2.imwrite(INPUT_NAME, img) img = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) Y = numpy.zeros((1, img.shape[0], img.shape[1], 1)) Y[0, :, :, 0] = img[:, :, 0] feature_map_visilization(model, Y)
def save_hough(self, lines, clmap): """ :param lines: (rho, theta) pairs :param clmap: clusters assigned to lines :return: None """ height, width = self.image.shape ratio = 600. * (self.step+1) / min(height, width) temp = cv2.resize(self.image, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_CUBIC) temp = cv2.cvtColor(temp, cv2.COLOR_GRAY2BGR) colors = [(0, 127, 255), (255, 0, 127)] for i in range(0, np.size(lines) / 2): rho = lines[i, 0] theta = lines[i, 1] color = colors[clmap[i, 0]] if theta < np.pi / 4 or theta > 3 * np.pi / 4: pt1 = (rho / np.cos(theta), 0) pt2 = (rho - height * np.sin(theta) / np.cos(theta), height) else: pt1 = (0, rho / np.sin(theta)) pt2 = (width, (rho - width * np.cos(theta)) / np.sin(theta)) pt1 = (int(pt1[0]), int(pt1[1])) pt2 = (int(pt2[0]), int(pt2[1])) cv2.line(temp, pt1, pt2, color, 5) self.save2image(temp)
def downscale(old_file_name): img = cv2.imread(os.path.join(old_file_name)) new_file_name = (old_file_name .replace('training', 'training_new') .replace('validation', 'validation_new') .replace('testing', 'testing_new') ) if 'instances' in new_file_name: img_new = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_LINEAR) else: img_new = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC) cv2.imwrite(new_file_name, img_new)
def resize(img, label, new_size, interpolation=cv2.INTER_CUBIC): """ Resizes the image TODO: Make this method more generic to modify the label Args: img: input image new_size: new image size [new_width,new_height] interpolation: Kind of interpolation to use """ return cv2.resize(img, new_size, interpolation=interpolation), label
def __init__(self, size, interpolation=cv2.INTER_CUBIC): self.size = size self.interpolation = interpolation