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)
python类INTER_CUBIC的实例源码
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)
operations.py 文件源码
项目:Smart-Surveillance-System-using-Raspberry-Pi
作者: OmkarPathak
项目源码
文件源码
阅读 26
收藏 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 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 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
processing.py 文件源码
项目:Ultras-Sound-Nerve-Segmentation---Kaggle
作者: Simoncarbo
项目源码
文件源码
阅读 41
收藏 0
点赞 0
评论 0
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
def __init__(self, size, interpolation=cv2.INTER_CUBIC):
self.size = size
self.interpolation = interpolation