Skip to content

Instantly share code, notes, and snippets.

@Z-Zheng
Created June 27, 2019 01:56
Show Gist options
  • Save Z-Zheng/8505047d7120c4a50279373ab9be5105 to your computer and use it in GitHub Desktop.
Save Z-Zheng/8505047d7120c4a50279373ab9be5105 to your computer and use it in GitHub Desktop.
sliding window
import numpy as np
import math
class OverlapSlidingWindow(object):
def __init__(self, image_shape, kernel_shape, stride):
self.stride_ = stride
self.image_shape_ = image_shape
self.kernel_shape_ = kernel_shape
ih, iw = self.image_shape_
kh, kw = self.kernel_shape_
assert ih >= kh and iw >= kw, ""
self.h_start = -self.stride_
self.w_start = -self.stride_
def window_iterator(self):
ih, iw = self.image_shape_
kh, kw = self.kernel_shape_
ncol = int(math.ceil((iw - kw) / self.stride_)) + 1
nrow = int(math.ceil((ih - kh) / self.stride_)) + 1
for i in range(nrow):
self.w_start = -self.stride_
self.h_start += self.stride_
for j in range(ncol):
self.w_start += self.stride_
h_end = min(self.h_start + kh, ih - 1)
w_end = min(self.w_start + kw, iw - 1)
hs = h_end - kh if h_end - self.h_start < kh else self.h_start
ws = w_end - kw if w_end - self.w_start < kw else self.w_start
yield hs, h_end, ws, w_end
class Matcher(object):
def __init__(self, boxes):
self._boxes = boxes
def is_inside(self, box, win):
ymin, xmin, ymax, xmax = box
wymin, wxmin, wymax, wxmax = win
return (wymin < ymin) and (wxmin < xmin) and (ymax < wymax) and (xmax < wxmax)
def is_overlap(self, box, win, thresh=0.8, nbox=None):
ymin, xmin, ymax, xmax = box
wymin, wxmin, wymax, wxmax = win
yminmax = max(ymin, wymin)
xminmax = max(xmin, wxmin)
ymaxmin = min(ymax, wymax)
xmaxmin = min(xmax, wxmax)
h = max(0, ymaxmin - yminmax)
w = max(0, xmaxmin - xminmax)
inter = h * w
overlap_ratio = inter / ((ymax - ymin) * (xmax - xmin))
if nbox is not None:
nbox[0] = max(0., yminmax + 1)
nbox[1] = max(0., xminmax + 1)
nbox[2] = max(0., ymaxmin - 1)
nbox[3] = max(0., xmaxmin - 1)
return overlap_ratio >= thresh
def match(self, win):
keeps = []
boxes = []
for idx, box in enumerate(self._boxes):
nbox = np.copy(box)
if self.is_inside(box, win):
keeps.append(idx)
boxes.append(box)
elif self.is_overlap(box, win, thresh=0.8, nbox=nbox):
keeps.append(idx)
boxes.append(nbox)
return keeps, np.asarray(boxes)
def coordinate_offset_left_top(abs_coord, left_top):
ymin, xmin, ymax, xmax = abs_coord
bymin, bxmin = left_top
ymin += bymin
ymax += bymin
xmin += bxmin
xmax += bxmin
return ymin, xmin, ymax, xmax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment