我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.copyMakeBorder()。
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE): def get_padding_size(image): h, w, _ = image.shape longest_edge = max(h, w) top, bottom, left, right = (0, 0, 0, 0) if h < longest_edge: dh = longest_edge - h top = dh // 2 bottom = dh - top elif w < longest_edge: dw = longest_edge - w left = dw // 2 right = dw - left else: pass return top, bottom, left, right top, bottom, left, right = get_padding_size(image) BLACK = [0, 0, 0] constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK) resized_image = cv2.resize(constant, (height, width)) return resized_image
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE): # def get_padding_size(image): # h, w, _ = image.shape # longest_edge = max(h, w) # top, bottom, left, right = (0, 0, 0, 0) # if h < longest_edge: # dh = longest_edge - h # top = dh // 2 # bottom = dh - top # elif w < longest_edge: # dw = longest_edge - w # left = dw // 2 # right = dw - left # else: # pass # return top, bottom, left, right # top, bottom, left, right = get_padding_size(image) # BLACK = [0, 0, 0] # constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK) # resized_image = cv2.resize(constant, (height, width)) resized_image = cv2.resize(image,(IMAGE_SIZE, IMAGE_SIZE)) return resized_image
def find_contours(mask, smooth_factor=0.005): """ Find the contours in a given mask """ border = 5 # Canny detection breaks down with the edge of the image my_mask = cv2.copyMakeBorder(mask, border, border, border, border, cv2.BORDER_CONSTANT, value=(0, 0, 0)) my_mask = cv2.cvtColor(my_mask, cv2.COLOR_BGR2GRAY) if is_cv2(): contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) else: _, contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # shift the contours back down for contour in contours: for pnt in contour: if pnt[0][1] > border: pnt[0][1] = pnt[0][1] - border else: pnt[0][1] = 0 if pnt[0][0] > border: pnt[0][0] = pnt[0][0] - border else: pnt[0][0] = 0 closed_contours = [] for contour in contours: epsilon = smooth_factor*cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) area = cv2.contourArea(approx) # if they are too small they are not edges if area < 200: continue closed_contours.append(approx) return closed_contours
def __getitem__(self, index): datafiles = self.files[index] image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR) size = image.shape name = osp.splitext(osp.basename(datafiles["img"]))[0] image = np.asarray(image, np.float32) image -= self.mean img_h, img_w, _ = image.shape pad_h = max(self.crop_h - img_h, 0) pad_w = max(self.crop_w - img_w, 0) if pad_h > 0 or pad_w > 0: image = cv2.copyMakeBorder(image, 0, pad_h, 0, pad_w, cv2.BORDER_CONSTANT, value=(0.0, 0.0, 0.0)) image = image.transpose((2, 0, 1)) return image, name, size
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE): def get_padding_size(image): h, w, _ = image.shape longest_edge = max(h, w) top, bottom, left, right = (0, 0, 0, 0) if h < longest_edge: dh = longest_edge - h top = dh // 2 bottom = dh - top elif w < longest_edge: dw = longest_edge - w left = dw // 2 right = dw - left else: pass return top, bottom, left, right top, bottom, left, right = get_padding_size(image) black = [0, 0, 0] constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=black) resized_image = cv2.resize(constant, (height, width)) return resized_image
def preallocate(self, img): if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]: h, w = img.shape[:2] self.size = (h, w) self.img = np.empty((h, w, 3), dtype=np.uint8) self.hsv = np.empty((h, w, 3), dtype=np.uint8) self.bin = np.empty((h, w, 1), dtype=np.uint8) self.bin2 = np.empty((h, w, 1), dtype=np.uint8) self.out = np.empty((h, w, 3), dtype=np.uint8) # for overlays self.zeros = np.zeros((h, w, 1), dtype=np.bool) self.black = np.zeros((h, w, 3), dtype=np.uint8) self.morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2), anchor=(0,0)) cv2.copyMakeBorder(img, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=self.RED, dst=self.out)
def __call__(self, img): """ Args: img (numpy.array): Image to be cropped. Returns: numpy.array: Cropped image. """ th, tw = self.size h, w = img.shape[:2] x1 = random.randint(0, w - tw) y1 = random.randint(0, h - th) if self.padding > 0: img = cv2.copyMakeBorder(img, self.padding, self.padding, self.padding, self.padding, self.pad_method, value=0) # sample crop locations if not given # it is necessary to keep cropping same in a video img_crop = img[y1:y1+th, x1:x1+tw] return img_crop
def __call__(self, imgs): """ Args: img (numpy.array): Image to be cropped. Returns: numpy.array: Cropped image. """ th, tw = self.size h, w = imgs[0].shape[:2] x1 = random.randint(0, w - tw) y1 = random.randint(0, h - th) for idx, img in enumerate(imgs): if self.padding > 0: img = cv2.copyMakeBorder(img, self.padding, self.padding, self.padding, self.padding, self.pad_method, value=0) # sample crop locations if not given # it is necessary to keep cropping same in a video img_crop = img[y1:y1+th, x1:x1+tw] imgs[idx] = img_crop return imgs
def __call__(self, img): """ Args: img (numpy.array): Image to be cropped. Returns: numpy.array: Cropped image. """ sample_w = random.choice(self.sample_sizes) sample_h = random.choice(self.sample_sizes) h, w = img.shape[:2] x1 = random.randint(0, w - sample_w) y1 = random.randint(0, h - sample_h) if self.padding > 0: img = cv2.copyMakeBorder(img, self.padding, self.padding, self.padding, self.padding, cv2.BORDER_CONSTANT, value=0) # sample crop locations if not given # it is necessary to keep cropping same in a video img_crop = img[y1:y1+sample_h, x1:x1+sample_w] return img_crop
def __call__(self, imgs): """ Args: img (numpy.array): Image to be cropped. Returns: numpy.array: Cropped image. """ sample_w = random.choice(self.sample_sizes) sample_h = random.choice(self.sample_sizes) h, w = imgs[0].shape[:2] x1 = random.randint(0, w - sample_w) y1 = random.randint(0, h - sample_h) for idx, img in enumerate(imgs): if self.padding > 0: img = cv2.copyMakeBorder(img, self.padding, self.padding, self.padding, self.padding, cv2.BORDER_CONSTANT, value=0) # sample crop locations if not given # it is necessary to keep cropping same in a video img_crop = img[y1:y1+sample_h, x1:x1+sample_w] imgs[idx] = img_crop return imgs
def setImage(self, img): ''' Call this function when you wish to write the image to disk. Not every image is written to disk. Makes a copy of the image. :param img: A numpy array representing an OpenCV image ''' if not self.active: return if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]: h, w = img.shape[:2] self.size = (h, w) self.out1 = np.empty((h, w, 3), dtype=np.uint8) self.out2 = np.empty((h, w, 3), dtype=np.uint8) with self.lock: cv2.copyMakeBorder(img, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=(0,0,255), dst=self.out1) self.has_image = True self.lock.notify()
def subwindow(img, window, borderType=cv2.BORDER_CONSTANT): cutWindow = [x for x in window] limit(cutWindow, [0, 0, img.shape[1], img.shape[0]]) # modify cutWindow assert(cutWindow[2] > 0 and cutWindow[3] > 0) border = getBorder(window, cutWindow) res = img[cutWindow[1]:cutWindow[1] + cutWindow[3], cutWindow[0]:cutWindow[0] + cutWindow[2]] if(border != [0, 0, 0, 0]): res = cv2.copyMakeBorder(res, border[1], border[3], border[0], border[2], borderType) return res # KCF tracker
def showResultMat(self, imgRotated, rect_size, center, index): m_width = 136 m_height = 36 imgCorp = cv2.getRectSubPix(imgRotated,rect_size,center) imgCorp = cv2.copyMakeBorder(imgCorp ,30,30,30,30,cv2.BORDER_CONSTANT,value=(0,0,0)) #constant = cv2.copyMakeBorder(closing ,30,30,30,30,cv2.BORDER_CONSTANT,value=255) imgCorp = self.inverseColor(imgCorp) print 'resize',imgCorp.shape if self.m_debug: picname = 'debug/rotate_fragment_'+str(index)+'.png' cv2.imwrite(picname,imgCorp) # imgResized = cv2.resize(imgCorp,(m_width,m_height)) # if self.m_debug: # picname = 'debug/rotate_fragment_resize_'+str(index)+'.png' # cv2.imwrite(picname,imgResized) return imgCorp # ?????? 0 ? 255, 255 ? 0
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0): """Pad image border Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray Parameters ---------- src : NDArray Image in (width, height, channels). Others are the same with cv2.copyMakeBorder Returns ------- img : NDArray padded image """ hdl = NDArrayHandle() check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot), ctypes.c_int(left), ctypes.c_int(right), ctypes.c_int(border_type), ctypes.c_double(value), ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
def 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) dest_h = int(2*src_r * scale) dest_w = int(2*src_r * scale) dh= (dest_h-org_h)/2 dw= (dest_w-org_w)/2 img=img_src if dh>0: img=cv2.copyMakeBorder(img,dh,dh,0,0,cv2.BORDER_CONSTANT,value=(0,0,0,0)) if dw>0: img=cv2.copyMakeBorder(img,0,0,dw,dw,cv2.BORDER_CONSTANT,value=(0,0,0,0)) return img, [dest_h,dest_w]
def randomShiftScale(img, u=0.25, limit=4): if random.random() < u: height, width, channel = img.shape assert (width == height) size0 = width size1 = width + 2 * limit img1 = cv2.copyMakeBorder(img, limit, limit, limit, limit, borderType=cv2.BORDER_REFLECT_101) size = round(random.uniform(size0, size1)) dx = round(random.uniform(0, size1 - size)) # pixel dy = round(random.uniform(0, size1 - size)) y1 = dy y2 = y1 + size x1 = dx x2 = x1 + size if size == size0: img = img1[y1:y2, x1:x2, :] else: img = cv2.resize(img1[y1:y2, x1:x2, :], (size0, size0), interpolation=cv2.INTER_LINEAR) return img
def process_image(img, img_size, pixel_depth): ''' Maintain aspect ratio of image while resizing ''' img = cv2.imread(img, cv2.IMREAD_COLOR) if (img.shape[0] >= img.shape[1]): # height is greater than width resizeto = (img_size, int( round(img_size * (float(img.shape[1]) / img.shape[0])))) else: resizeto = ( int(round(img_size * (float(img.shape[0]) / img.shape[1]))), img_size) img = cv2.resize(img, (resizeto[1], resizeto[ 0]), interpolation=cv2.INTER_CUBIC) img = cv2.copyMakeBorder( img, 0, img_size - img.shape[0], 0, img_size - img.shape[1], cv2.BORDER_CONSTANT, 0) img = normalize_image(img, pixel_depth) return img[:, :, ::-1] # turn into rgb format
def _pad_image(self, im): return cv2.copyMakeBorder(im,19,20,24,25,cv2.BORDER_CONSTANT,value=[0,0,0] if im.ndim == 3 else 0)
def im_pad(im, pad=3, value=0): return cv2.copyMakeBorder(im, pad, pad, pad, pad, cv2.BORDER_CONSTANT, value)
def create_border(frame, height, width, color): """Add constant border for the frame. The original frame will be displayed at the center of the monitor Parameters ---------- frame : OpenCV Mat the original frame of image or video height : int height of the monitor width : int width of the monitor color : list the color of the border Returns ------- new_frame : OpenCV Mat border added OpenCV Mat """ vert = height/2-frame.shape[0]/2 hor = width/2-frame.shape[1]/2 new_frame = cv2.copyMakeBorder(src=frame, top=vert, bottom=vert, left=hor, right=hor, borderType=cv2.BORDER_CONSTANT, value=color) return new_frame
def rescale_image(frame, swin_h, swin_w, color=[255, 0, 0]): """Rescale image to size of working window. Parameters --------- frame : numpy.ndarray given image or frame swin_h : int width of the working window swin_w : int height of the working window color : list The background color of appended border """ # new_frame = frame.copy() # try to save memory new_frame = frame frame_h = frame.shape[0] frame_w = frame.shape[1] # if the ratio is different, then append border if (float(swin_h)/float(swin_w)) != (float(frame_h)/float(frame_w)): # do something if (float(frame_h)/float(frame_w)) > (float(swin_h)/float(swin_w)): w_append = int((frame_h*swin_w-swin_h*frame_w)/swin_h) new_frame = cv2.copyMakeBorder(src=new_frame, top=0, bottom=0, left=w_append/2, right=w_append/2, borderType=cv2.BORDER_CONSTANT, value=color) elif (float(frame_h)/float(frame_w)) < (float(swin_h)/float(swin_w)): h_append = int((swin_h*frame_w-frame_h*swin_w)/swin_w) new_frame = cv2.copyMakeBorder(src=new_frame, top=h_append/2, bottom=h_append/2, left=0, right=0, borderType=cv2.BORDER_CONSTANT, value=color) new_frame = cv2.resize(new_frame, (swin_w, swin_h), interpolation=cv2.INTER_AREA) return new_frame
def __call__(self, img): if self.padding == 0: return img p = self.padding res = cv2.copyMakeBorder(img, p, p, p, p, borderType=self.borderType, value=self.borderValue) return res[:, :, np.newaxis] if np.ndim(res) == 2 else res
def resize_to_desired(input_img): h = input_img.shape[0] if h < 20: # pad the image to 20 or 21 pixels height if it is too short border = math.ceil((20 - h) / 2) new_img = cv2.copyMakeBorder(input_img, top=border, bottom=border, left=0, right=0, borderType=cv2.BORDER_DEFAULT) else: new_img = input_img return cv2.resize(new_img, (CLS_IMG_WIDTH, CLS_IMG_HEIGHT))
def read_image(file_path): img = cv2.imread(file_path, cv2.IMREAD_COLOR) # cv2.IMREAD_GRAYSCALE if (img.shape[0] >= img.shape[1]): # height is greater than width resizeto = (IMAGE_SIZE, int(round(IMAGE_SIZE * (float(img.shape[1]) / img.shape[0])))); else: resizeto = (int(round(IMAGE_SIZE * (float(img.shape[0]) / img.shape[1]))), IMAGE_SIZE); img2 = cv2.resize(img, (resizeto[1], resizeto[0]), interpolation=cv2.INTER_CUBIC) img3 = cv2.copyMakeBorder(img2, 0, IMAGE_SIZE - img2.shape[0], 0, IMAGE_SIZE - img2.shape[1], cv2.BORDER_CONSTANT, 0) return img3[:, :, ::-1] # turn into rgb format
def prep_img_save(img, b=5): return cv2.normalize(cv2.copyMakeBorder(img, b, b, b, b, cv2.BORDER_CONSTANT, value=0), 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
def find_chessboard_corners(greyscale_image, neighborhood_size=10, candidate_threshold=.5): candidates = find_candidates(greyscale_image, neighborhood_size, candidate_threshold) bordered_image = cv2.copyMakeBorder(greyscale_image, neighborhood_size, neighborhood_size, neighborhood_size, neighborhood_size, cv2.BORDER_CONSTANT, value=0) detected_corners = [] windows = [] grad_mags = [] templates = [] ix_candidate = 0 for candidate in candidates: print(ix_candidate) coord = candidate window = greyscale_image[coord[0] - neighborhood_size:coord[0] + neighborhood_size + 1, coord[1] - neighborhood_size:coord[1] + neighborhood_size + 1] hist, grad_mag = __filter_candidate(bordered_image, candidate, neighborhood_size) win_b = cv2.copyMakeBorder(window, 5, 5, 5, 5, cv2.BORDER_CONSTANT, value=0) windows.append(win_b) grad_mags.append(prep_img_save(grad_mag)) angles = __find_dominant_directions(hist) if angles is not None: template = __build_corner_template(neighborhood_size * 2 + 1, angles) templates.append(prep_img_save(template)) else: templates.append(np.zeros_like(win_b)) ix_candidate += 1 # if __filter_candidate(bordered_image, candidate, neighborhood_size): # detected_corners.append(candidate) ch_test = np.vstack((np.hstack(windows), np.hstack(grad_mags), np.hstack(templates))) cv2.imwrite("~/Desktop/TMP/ch_test01.png", ch_test) detected_corners = np.array(detected_corners) # return detected_corners return candidates
def __getitem__(self, index): datafiles = self.files[index] image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR) label = cv2.imread(datafiles["label"], cv2.IMREAD_GRAYSCALE) size = image.shape name = datafiles["name"] if self.scale: image, label = self.generate_scale_label(image, label) image = np.asarray(image, np.float32) image -= self.mean img_h, img_w = label.shape pad_h = max(self.crop_h - img_h, 0) pad_w = max(self.crop_w - img_w, 0) if pad_h > 0 or pad_w > 0: img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0, pad_w, cv2.BORDER_CONSTANT, value=(0.0, 0.0, 0.0)) label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0, pad_w, cv2.BORDER_CONSTANT, value=(self.ignore_label,)) else: img_pad, label_pad = image, label img_h, img_w = label_pad.shape h_off = random.randint(0, img_h - self.crop_h) w_off = random.randint(0, img_w - self.crop_w) # roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h); image = np.asarray(img_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32) label = np.asarray(label_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32) #image = image[:, :, ::-1] # change to BGR image = image.transpose((2, 0, 1)) if self.is_mirror: flip = np.random.choice(2) * 2 - 1 image = image[:, :, ::flip] label = label[:, ::flip] return image.copy(), label.copy(), np.array(size), name
def threshold(self, img): cv2.cvtColor(img, cv2.COLOR_BGR2HSV, dst=self.hsv) cv2.inRange(self.hsv, self.thresh_low, self.thresh_high, dst=self.bin) cv2.morphologyEx(self.bin, cv2.MORPH_CLOSE, self.morphKernel, dst=self.bin2, iterations=1) if self.draw_thresh: b = (self.bin2 != 0) cv2.copyMakeBorder(self.black, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=self.RED, dst=self.out) self.out[np.dstack((b, b, b))] = 255 return self.bin2
def _pad_image(self, image, joint): height, width, _ = image.shape shape = np.array((width, height)) residual = (self.image_size - shape).clip(0, self.image_size) left, top = residual/2 right, bottom = residual - residual/2 padded_image = cv2.copyMakeBorder( image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=0) moved_joint = joint + (left, top, 0) return padded_image, moved_joint
def getDarkMap(img,pitchSize=9): darkMap=np.zeros(shape=(img.shape[0],img.shape[1]),dtype=np.uint8) #padding,and darkMap has the same shape with the img # print ("shape of darkmap",darkMap.shape[0],darkMap.shape[1]) padSize=(pitchSize-1)//2 #print ("type of pitchsize",type(padSize)) pad=cv2.copyMakeBorder(img,padSize,padSize,padSize,padSize,cv2.BORDER_CONSTANT,value=255) for i in range(darkMap.shape[0]): for j in range(darkMap.shape[1]): darkMap[i,j]=pad[i:i+pitchSize,j:j+pitchSize].min() return pad,darkMap
def pad_height(image): height, width, _ = image.shape border_x = 0 border_y = int(round(1080-height)/2.) image = cv2.copyMakeBorder(image, border_y, border_y, border_x, border_x, cv2.BORDER_CONSTANT, value=[0,0,0,0]) return image
def pad_width(image): height, width, _ = image.shape border_x = int(round(1920-width)/2.) border_y = 0 image = cv2.copyMakeBorder(image, border_y, border_y, border_x, border_x, cv2.BORDER_CONSTANT, value=[0,0,0,0]) return image
def frame(image, top=2, bottom=2, left=2, right=2, borderType=cv.BORDER_CONSTANT, color=[255, 0, 0]): ''' add borders around :image: :param image: has to be in RBG color scheme. Use `convert_to_rgb` if it's in opencv BGR scheme. :param color: array representing an RGB color. :param borderType: Other options are: cv.BORDER_REFLECT, cv.BORDER_REFLECT_101, cv.BORDER_DEFAULT, cv.BORDER_REPLICATE, cv.BORDER_WRAP ''' return cv.copyMakeBorder(image, top, bottom, left, right, borderType, value=color)
def add_border(src): dst = np.empty(shape=(src.shape[0], src.shape[1] + 2 * image_border, src.shape[2] + 2 * image_border)) for c in xrange(src.shape[0]): dst[c] = cv2.copyMakeBorder(src[c], top=image_border, bottom=image_border, left=image_border, right=image_border, borderType=cv2.BORDER_REPLICATE) return dst
def MotionBlur(img, steps): ''' Parameters: ----------- img: Ndarray. CV loaded image steps: tuple(step_x, step_y). Motion Velocity Return: ------- img: Ndarray. Blurred image ''' BLACK=[0,0,0] img_height, img_width, channel= img.shape step_x , step_y = steps hori = abs(step_x) vert = abs(step_y) img_mb = cv.copyMakeBorder(img, vert, vert, hori, hori, cv.BORDER_CONSTANT, value=BLACK) img_mask = np.zeros((img_height,img_width, channel)) if step_x!=0 : sign_x = step_x / hori for x in xrange(0, hori): img_mask += img_mb[vert : vert+img_height, hori-x*sign_x : hori+img_width-x*sign_x] if step_y!=0 : sign_y = step_y / vert for y in xrange(0, vert): img_mask += img_mb[vert-y*sign_y : vert+img_height-y*sign_y, hori:hori+img_width] img_mask /= (hori+vert) return img_mask
def _draw_bbox(self, img): h, w = img.shape[:2] canvas = cv2.copyMakeBorder(img, 0, BAR_HEIGHT, 0, 0, cv2.BORDER_CONSTANT, value=COLOR_GRAY) label_msg = '{}: {}, {}'.format(self._cur_label, self._pt0, self._pt1) \ if self._drawing \ else 'Current label: {}'.format(self._cur_label) msg = '{}/{}: {} | {}'.format(self._index + 1, len(self._filelist), self._filelist[self._index], label_msg) cv2.putText(canvas, msg, (1, h+12), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) for label, (bpt0, bpt1) in self._bboxes: label_color = self.label_colors[label] if label in self.label_colors else COLOR_GRAY cv2.rectangle(canvas, bpt0, bpt1, label_color, thickness=2) cv2.putText(canvas, label, (bpt0[0]+3, bpt0[1]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, label_color, 2) if self._drawing: label_color = self.label_colors[self._cur_label] if self._cur_label in self.label_colors else COLOR_GRAY if self._pt1[0] >= self._pt0[0] and self._pt1[1] >= self._pt0[1]: cv2.rectangle(canvas, self._pt0, self._pt1, label_color, thickness=2) cv2.putText(canvas, self._cur_label, (self._pt0[0] + 3, self._pt0[1] + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, label_color, 2) return canvas
def preprocess(self): self.resizeCaptcha() # ??? img_thresh = self.th1(self.img) if self.m_debug: cv2.imshow("thres", img_thresh) cv2.imwrite("debug/threshold.png", img_thresh) # ????? ??? kernel = np.ones((2,2),np.uint8) closing = cv2.morphologyEx(img_thresh , cv2.MORPH_CLOSE, kernel) if self.m_debug: cv2.imshow("close", closing) cv2.imwrite("debug/closing.png",closing) # ???? constant = cv2.copyMakeBorder(closing ,50,50,50,50,cv2.BORDER_CONSTANT,value=255) # ??????? 0 ? 255?? # inverse binary image # constant = self.inverseColor(constant) # ?? constantSrc = cv2.merge((constant,constant,constant)) if self.m_debug: cv2.imwrite("debug/broader.png",constantSrc) self.imgPreprocess = constantSrc.copy()
def __call__(self, image, *args): size=self.size if self.type=='constant': image = cv2.copyMakeBorder(image, size, size, size, size, cv2.BORDER_CONSTANT, value=self.constant_color) elif self.type=='reflect': image = cv2.copyMakeBorder(image, size, size, size, size, cv2.BORDER_REFLECT) elif self.type=='replicate': image = cv2.copyMakeBorder(image, size, size, size, size, cv2.BORDER_REPLICATE) if len(args): return (image, *args) else: return image
def center_crop(img, length): if img.shape[0] < length or img.shape[1] < length: top = max(0, int(np.ceil((length - img.shape[0]) / 2.))) left = max(0, int(np.ceil((length - img.shape[1]) / 2.))) img = cv2.copyMakeBorder( img, top, top, left, left, borderType=cv2.BORDER_REFLECT_101 ) crop_y = int(np.floor((img.shape[0] - length) / 2.)) crop_x = int(np.floor((img.shape[1] - length) / 2.)) crop = img[crop_y:crop_y + length, crop_x:crop_x + length] return crop
def random_scale_img(img, xy_range, lock_xy=False): if random.random() > xy_range.chance: return img if not isinstance(img, list): img = [img] import cv2 scale_x = random.uniform(xy_range.x_min, xy_range.x_max) scale_y = random.uniform(xy_range.y_min, xy_range.y_max) if lock_xy: scale_y = scale_x org_height, org_width = img[0].shape[:2] xy_range.last_x = scale_x xy_range.last_y = scale_y res = [] for img_inst in img: scaled_width = int(org_width * scale_x) scaled_height = int(org_height * scale_y) scaled_img = cv2.resize(img_inst, (scaled_width, scaled_height), interpolation=cv2.INTER_CUBIC) if scaled_width < org_width: extend_left = (org_width - scaled_width) / 2 extend_right = org_width - extend_left - scaled_width scaled_img = cv2.copyMakeBorder(scaled_img, 0, 0, extend_left, extend_right, borderType=cv2.BORDER_CONSTANT) scaled_width = org_width if scaled_height < org_height: extend_top = (org_height - scaled_height) / 2 extend_bottom = org_height - extend_top - scaled_height scaled_img = cv2.copyMakeBorder(scaled_img, extend_top, extend_bottom, 0, 0, borderType=cv2.BORDER_CONSTANT) scaled_height = org_height start_x = (scaled_width - org_width) / 2 start_y = (scaled_height - org_height) / 2 tmp = scaled_img[start_y: start_y + org_height, start_x: start_x + org_width] res.append(tmp) return res
def randomShift(img, u=0.25, limit=4): if random.random() < u: dx = round(random.uniform(-limit, limit)) # pixel dy = round(random.uniform(-limit, limit)) # pixel height, width, channel = img.shape img1 = cv2.copyMakeBorder(img, limit + 1, limit + 1, limit + 1, limit + 1, borderType=cv2.BORDER_REFLECT_101) y1 = limit + 1 + dy y2 = y1 + height x1 = limit + 1 + dx x2 = x1 + width img = img1[y1:y2, x1:x2, :] return img