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
python类BORDER_CONSTANT的实例源码
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.
"""
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 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 _do_filter(self, frame):
''' Process a single frame. '''
# blur to reduce noise
frame = cv2.GaussianBlur(frame, (5, 5), 0, borderType=cv2.BORDER_CONSTANT)
# threshold to find contiguous regions of "bright" pixels
# ignore all "dark" (<1/8 max) pixels
max = numpy.max(frame)
min = numpy.min(frame)
# if the frame is completely dark, then just return it
if max == min:
return frame
threshold = min + (max - min) / 8
_, frame = cv2.threshold(frame, threshold, 255, cv2.THRESH_BINARY)
# filter out single pixels and other noise
frame = cv2.erode(frame, self._element_shrink)
# restore and join nearby regions (in case one fish has a skinny middle...)
frame = cv2.dilate(frame, self._element_grow)
return frame
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 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]
step2_train_mass_segmenter.py 文件源码
项目:kaggle_ndsb2017
作者: juliandewit
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def random_translate_img(img, xy_range, border_mode="constant"):
if random.random() > xy_range.chance:
return img
import cv2
if not isinstance(img, list):
img = [img]
org_height, org_width = img[0].shape[:2]
translate_x = random.randint(xy_range.x_min, xy_range.x_max)
translate_y = random.randint(xy_range.y_min, xy_range.y_max)
trans_matrix = numpy.float32([[1, 0, translate_x], [0, 1, translate_y]])
border_const = cv2.BORDER_CONSTANT
if border_mode == "reflect":
border_const = cv2.BORDER_REFLECT
res = []
for img_inst in img:
img_inst = cv2.warpAffine(img_inst, trans_matrix, (org_width, org_height), borderMode=border_const)
res.append(img_inst)
if len(res) == 1:
res = res[0]
xy_range.last_x = translate_x
xy_range.last_y = translate_y
return res
step2_train_mass_segmenter.py 文件源码
项目:kaggle_ndsb2017
作者: juliandewit
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def random_rotate_img(img, chance, min_angle, max_angle):
import cv2
if random.random() > chance:
return img
if not isinstance(img, list):
img = [img]
angle = random.randint(min_angle, max_angle)
center = (img[0].shape[0] / 2, img[0].shape[1] / 2)
rot_matrix = cv2.getRotationMatrix2D(center, angle, scale=1.0)
res = []
for img_inst in img:
img_inst = cv2.warpAffine(img_inst, rot_matrix, dsize=img_inst.shape[:2], borderMode=cv2.BORDER_CONSTANT)
res.append(img_inst)
if len(res) == 0:
res = res[0]
return res
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 randomShiftScaleRotate(img, shift_limit=0.0625, scale_limit=0.1, rotate_limit=45, u=0.5):
if random.random() < u:
height, width, channel = img.shape
angle = random.uniform(-rotate_limit, rotate_limit) # degree
scale = random.uniform(1 - scale_limit, 1 + scale_limit)
dx = round(random.uniform(-shift_limit, shift_limit)) * width
dy = round(random.uniform(-shift_limit, shift_limit)) * height
cc = math.cos(angle / 180 * math.pi) * (scale)
ss = math.sin(angle / 180 * math.pi) * (scale)
rotate_matrix = np.array([[cc, -ss], [ss, cc]])
box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])
box1 = box0 - np.array([width / 2, height / 2])
box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])
box0 = box0.astype(np.float32)
box1 = box1.astype(np.float32)
mat = cv2.getPerspectiveTransform(box0, box1)
img = cv2.warpPerspective(img, mat, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REFLECT_101) # cv2.BORDER_CONSTANT, borderValue = (0, 0, 0)) #cv2.BORDER_REFLECT_101
return img
preprocess_images.py 文件源码
项目:Kaggle-Cat-vs-Dog-Tensorflow-CNN
作者: jshin49
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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 test_box_filter_zero(self):
I = np.array(range(1, 50)).reshape(7, 7).astype(np.float32)
r = 2
ret1 = cv.smooth.box_filter(I, r, normalize=True, border_type='zero')
ret2 = cv2.blur(I, (5,5), borderType=cv2.BORDER_CONSTANT)
self.assertTrue(np.array_equal(ret1, ret2))
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 __init__(self, padding, borderType=cv2.BORDER_CONSTANT, borderValue=0):
assert isinstance(padding, numbers.Number)
self.padding = padding
self.borderType = borderType
self.borderValue = borderValue
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