def read_img(path, s_size):
image1 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
if image1.shape[0] < image1.shape[1]:
s0 = s_size
s1 = int(image1.shape[1] * (s_size / image1.shape[0]))
s1 = s1 - s1 % 16
else:
s1 = s_size
s0 = int(image1.shape[0] * (s_size / image1.shape[1]))
s0 = s0 - s0 % 16
image1 = np.asarray(image1, np.float32)
image1 = cv2.resize(image1, (s1, s0), interpolation=cv2.INTER_AREA)
if image1.ndim == 2:
image1 = image1[:, :, np.newaxis]
return image1.transpose(2, 0, 1), False
python类INTER_AREA的实例源码
def resize_sample(sample, shape=None, use_interp=True, scale=None):
if (shape and scale) or (not shape and not scale):
raise ValueError('Must specify exactly one of shape or scale, but got shape=\'{}\', scale=\'{}\''.format(shape, scale))
# Use INTER_AREA for shrinking and INTER_LINEAR for enlarging:
interp = cv2.INTER_NEAREST
if use_interp:
target_is_smaller = (shape and shape[1] < sample.shape[1]) or (scale and scale < 1) # targetWidth < sampleWidth
interp = cv2.INTER_AREA if target_is_smaller else cv2.INTER_LINEAR
if shape:
resized = cv2.resize(sample, (shape[1], shape[0]), interpolation=interp)
else:
resized = cv2.resize(sample, None, fx=scale, fy=scale, interpolation=interp)
return resized
def imresample(img, sz):
im_data = cv2.resize(img, (sz[1], sz[0]), interpolation=cv2.INTER_AREA) #@UndefinedVariable
return im_data
# This method is kept for debugging purpose
# h=img.shape[0]
# w=img.shape[1]
# hs, ws = sz
# dx = float(w) / ws
# dy = float(h) / hs
# im_data = np.zeros((hs,ws,3))
# for a1 in range(0,hs):
# for a2 in range(0,ws):
# for a3 in range(0,3):
# im_data[a1,a2,a3] = img[int(floor(a1*dy)),int(floor(a2*dx)),a3]
# return im_data
def scale(image, new_size, kind='width'):
''' resize :image: to :new_size: param while preserving aspect ratio. '''
# obtain image height & width.
h, w, channels = image.shape
# aspect ratio = original width / original height.
aspect_ratio = w / h
if kind == 'width':
if w > new_size:
# adjusted height.
new_height = int(new_size // aspect_ratio)
# inter_area for resizing algorithm parameter.
return cv.resize(image, (new_size, new_height), interpolation=cv.INTER_AREA)
elif kind == 'height':
if h > new_size:
# adjusted width.
new_width = int(new_size // aspect_ratio)
# inter_area for resizing algorithm parameter.
return cv.resize(image, (new_width, new_size), interpolation=cv.INTER_AREA)
else:
raise ValueError('Not supported option.')
operations.py 文件源码
项目:Smart-Surveillance-System-using-Raspberry-Pi
作者: OmkarPathak
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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 random_augmentation(image, crop_size, resize_size):
# randomly choose crop size
image = image.transpose(1, 2, 0)
h, w, _ = image.shape
# random cropping
if crop_size != h:
top = random.randint(0, h - crop_size - 1)
left = random.randint(0, w - crop_size - 1)
bottom = top + crop_size
right = left + crop_size
image = image[top:bottom, left:right, :]
# random flipping
if random.randint(0, 1):
image = image[:, ::-1, :]
# randomly choose resize size
if resize_size != crop_size:
cv2.resize(image, (resize_size, resize_size), interpolation=cv2.INTER_AREA)
return image.transpose(2, 0, 1)
def multi_feat_match(template, image, options=None):
"""
Match template and image by extracting multiple features (specified) from it.
:param template: Template image
:param image: Search image
:param options: Options include
- features: List of options for each feature
:return:
"""
h, w = image.shape[:2]
scale = 1
if options is not None and 'features' in options:
heatmap = np.zeros((h, w), dtype=np.float64)
for foptions in options['features']:
f_hmap, _ = feature_match(template, image, foptions)
heatmap += cv.resize(f_hmap, (w, h), interpolation=cv.INTER_AREA)
heatmap /= len(options['features'])
else:
heatmap, scale = feature_match(template, image, options)
return heatmap, scale
def generate_data(train_path, test_path):
index = 1
output_index = 1
for (dirpath, dirnames, filenames) in os.walk(input_path):
# ???????????????8?????2???
random.shuffle(filenames)
for filename in filenames:
if filename.endswith('.bmp'):
img_path = dirpath + '/' + filename
# ??opencv ????
img_data = cv2.imread(img_path)
# ??????????????28 * 28
img_data = cv2.resize(img_data, (28, 28), interpolation=cv2.INTER_AREA)
if index < 3:
cv2.imwrite(test_path + '/' + str(output_index) + '/' + str(index) + '.jpg', img_data)
index += 1
elif 10 >= index >= 3:
cv2.imwrite(train_path + '/' + str(output_index) + '/' + str(index) + '.jpg', img_data)
index += 1
if index > 10:
output_index += 1
index = 1
def feed(self, im):
assert im.dtype == np.uint8
im = cv2.resize(im, dsize=self.im_shape, interpolation=cv2.INTER_AREA)
im = im - 127.5
ss = [None]*len(self.Vs)
cs = [None]*len(self.Vs)
inp = im
for i, Vn in enumerate(self.Vs):
n = i + 1
if self.Vs[i].use_feedback and (i+1) < len(self.Vs):
context = self.gen_context(self.Vs[i+1], self.im_shape[0]/self.Vs[0].Xb/(2**i), self.im_shape[1]/self.Vs[0].Yb/(2**i))
else:
context = None # top level doesn't have any feedback
s, c = self.Vs[i].sparsify(inp, context=context)
ss[i] = s
cs[i] = c
if c is None: # sparsify returns None if a layer isn't trained enough to return a response
break
if n < len(self.Vs):
# input for next level
inp = self.group_NxN_input(c, 2, self.Vs[0].K+1, self.im_shape[0]/self.Vs[0].Xb/(2**i), self.im_shape[1]/self.Vs[0].Yb/(2**i))
return ss, cs
def createTrainingInstances(self, images):
hog = cv2.HOGDescriptor()
instances = []
for img, label in images:
print img
img = read_color_image(img)
img = cv2.resize(img, (128, 128), interpolation = cv2.INTER_AREA)
descriptor = hog.compute(img)
if descriptor is None:
descriptor = []
else:
descriptor = descriptor.ravel()
pairing = Instance(descriptor, label)
instances.append(pairing)
self.training_instances = instances
def createTestingInstances(self, images):
hog = cv2.HOGDescriptor()
instances = []
for img, label in images:
print img
img = read_color_image(img)
img = cv2.resize(img, (128, 128), interpolation = cv2.INTER_AREA)
descriptor = hog.compute(img)
if descriptor is None:
descriptor = []
else:
descriptor = descriptor.ravel()
pairing = Instance(descriptor, label)
instances.append(pairing)
self.testing_instances = instances
def local_hog(image):
HOGDESC = cv2.HOGDescriptor()
img, label = image
img = read_color_image(img)
img = cv2.resize(img, (128, 128), interpolation = cv2.INTER_AREA)
descriptor = HOGDESC.compute(img)
if descriptor is None:
descriptor = []
else:
descriptor = descriptor.ravel()
pairing = Instance(descriptor, label)
return pairing
def local_par_hog(images):
inst = list()
HOGDESC = cv2.HOGDescriptor()
for image in images:
img, label = image
img = read_color_image(img)
img = cv2.resize(img, (128, 128), interpolation = cv2.INTER_AREA)
descriptor = HOGDESC.compute(img)
if descriptor is None:
descriptor = []
else:
descriptor = descriptor.ravel()
pairing = Instance(descriptor, label)
inst.append(pairing)
return inst
def compare_io(X_val, model_raw, directory = '%s/image_comparison' % cfg['dir']['validation']):
#Creates tensors to compare to source images, plots both side by side, and saves the plots
road = Roadgen(cfg)
curves_to_print = model_raw.shape[0]
#reshaping the model output vector to make it easier to work with
model_out = road.model_interpret(model_raw)
print('predictions denormalized')
#initialize the model view tensor
model_view = np.zeros( (curves_to_print, road.input_size[1], road.input_size[0],
road.n_channels), dtype=np.uint8)
for prnt_i in range(curves_to_print):
patch = road.road_generator(model_out[prnt_i], road.line_width, rand_gen=0)
model_view[prnt_i] = cv2.resize(patch, road.input_size, interpolation=cv2.INTER_AREA)
road.save_images(X_val, model_view, directory )
#Prints plot of curves against the training data Saves plots in files
#Because the model outputs are not put into a drawing function it is easier for audiences
# to understand the model output data.
#FIXME function is still built to work like v1 generation also may have bugs in the plotter function
def resize(image, width=None, height=None, interpolation=cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the original image
if width is None and height is None: return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation = interpolation)
# return the resized image
return resized
def load_images(queue: PriorityQueue,
source: int,
file_path: str,
target_width: int,
target_height: int,
display_progress: bool=False):
window = 'image'
if display_progress:
cv2.namedWindow(window)
for file in iglob(path.join(file_path, '**', '*.jpg'), recursive=True):
buffer = cv2.imread(file)
buffer = cv2.resize(buffer, (target_width, target_height), interpolation=cv2.INTER_AREA)
random_priority = random()
queue.put((random_priority, (buffer, source)))
if display_progress:
cv2.imshow(window, buffer)
if (cv2.waitKey(33) & 0xff) == 27:
break
if display_progress:
cv2.destroyWindow(window)
def pad(im, scale=1.3, size=224):
"""Pad im with 0"""
h = im.shape[0]
w = im.shape[1]
pad_value = 128
if h>scale*w:
scale = 1.0*h/size
new_im = cv2.resize(im,(int(w/scale),size),interpolation=cv2.INTER_AREA)
pad_size = (size - new_im.shape[1])/2
padding = ((0,0),(pad_size,pad_size),(0,0))
new_im = np.pad(new_im, padding, mode = 'constant', constant_values=(pad_value,pad_value))
return new_im
if w>scale*h:
scale = 1.0*w/size
new_im = cv2.resize(im,(size,int(h/scale)),interpolation=cv2.INTER_AREA)
pad_size = (size - new_im.shape[0])/2
padding = ((pad_size,pad_size),(0,0),(0,0))
new_im = np.pad(new_im, padding, mode = 'constant', constant_values = (pad_value,pad_value))
return new_im
return im
def pad(im, scale=10, size=224):
"""Pad im with pad_value"""
pad_value = 128
h = im.shape[0]
w = im.shape[1]
if h>scale*w:
scale = 1.0*h/size
#new_im = im
new_im = cv2.resize(im,(int(w/scale),size),interpolation=cv2.INTER_AREA)
pad_size = (size - new_im.shape[1])/2
padding = ((0,0),(pad_size,pad_size),(0,0))
new_im = np.pad(new_im, padding, mode = 'constant', constant_values=(pad_value,pad_value))
return new_im
if w>scale*h:
scale = 1.0*w/size
#new_im = im
new_im = cv2.resize(im,(size,int(h/scale)),interpolation=cv2.INTER_AREA)
pad_size = (size - new_im.shape[0])/2
padding = ((pad_size,pad_size),(0,0),(0,0))
new_im = np.pad(new_im, padding, mode = 'constant', constant_values = (pad_value,pad_value))
return new_im
return cv2.resize(im, (size,size), interpolation=cv2.INTER_AREA)
def imresample(img, sz):
im_data = cv2.resize(img, (sz[1], sz[0]), interpolation=cv2.INTER_AREA) #@UndefinedVariable
return im_data
# This method is kept for debugging purpose
# h=img.shape[0]
# w=img.shape[1]
# hs, ws = sz
# dx = float(w) / ws
# dy = float(h) / hs
# im_data = np.zeros((hs,ws,3))
# for a1 in range(0,hs):
# for a2 in range(0,ws):
# for a3 in range(0,3):
# im_data[a1,a2,a3] = img[int(floor(a1*dy)),int(floor(a2*dx)),a3]
# return im_data
def imresample(img, sz):
im_data = cv2.resize(img, (sz[1], sz[0]), interpolation=cv2.INTER_AREA) #pylint: disable=no-member
return im_data
# This method is kept for debugging purpose
# h=img.shape[0]
# w=img.shape[1]
# hs, ws = sz
# dx = float(w) / ws
# dy = float(h) / hs
# im_data = np.zeros((hs,ws,3))
# for a1 in range(0,hs):
# for a2 in range(0,ws):
# for a3 in range(0,3):
# im_data[a1,a2,a3] = img[int(floor(a1*dy)),int(floor(a2*dx)),a3]
# return im_data