Python cv2.NORM_MINMAX Examples

The following are 30 code examples of cv2.NORM_MINMAX(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: video2tfrecord.py    From video2tfrecord with MIT License 8 votes vote down vote up
def compute_dense_optical_flow(prev_image, current_image):
  old_shape = current_image.shape
  prev_image_gray = cv2.cvtColor(prev_image, cv2.COLOR_BGR2GRAY)
  current_image_gray = cv2.cvtColor(current_image, cv2.COLOR_BGR2GRAY)
  assert current_image.shape == old_shape
  hsv = np.zeros_like(prev_image)
  hsv[..., 1] = 255
  flow = None
  flow = cv2.calcOpticalFlowFarneback(prev=prev_image_gray,
                                      next=current_image_gray, flow=flow,
                                      pyr_scale=0.8, levels=15, winsize=5,
                                      iterations=10, poly_n=5, poly_sigma=0,
                                      flags=10)

  mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
  hsv[..., 0] = ang * 180 / np.pi / 2
  hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
  return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) 
Example #2
Source File: tracking.py    From OpenCV-Computer-Vision-Projects-with-Python with MIT License 8 votes vote down vote up
def _update_mean_shift_bookkeeping(self, frame, box_grouped):
        """Preprocess all valid bounding boxes for mean-shift tracking

            This method preprocesses all relevant bounding boxes (those that
            have been detected by both mean-shift tracking and saliency) for
            the next mean-shift step.

            :param frame: current RGB input frame
            :param box_grouped: list of bounding boxes
        """
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        self.object_roi = []
        self.object_box = []
        for box in box_grouped:
            (x, y, w, h) = box
            hsv_roi = hsv[y:y + h, x:x + w]
            mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                               np.array((180., 255., 255.)))
            roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
            cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

            self.object_roi.append(roi_hist)
            self.object_box.append(box) 
Example #3
Source File: imgproc.py    From graph_distillation with Apache License 2.0 6 votes vote down vote up
def proc_oflow(images):
  h, w = images.shape[-3:-1]

  processed_images = []
  for image in images:
    hsv = np.zeros((h, w, 3), dtype=np.uint8)
    hsv[:, :, 0] = 255
    hsv[:, :, 1] = 255

    mag, ang = cv2.cartToPolar(image[..., 0], image[..., 1])
    hsv[..., 0] = ang*180/np.pi/2
    hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)

    processed_image = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    processed_images.append(processed_image)

  return np.stack(processed_images) 
Example #4
Source File: FOVMultiWellsSplitter.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def get_blur_im(self):
        """downscale and blur the image"""
        # preprocess image
        dwnscl_factor = 4; # Hydra images' shape is divisible by 4
        blr_sigma = 17; # blur the image a bit, seems to work better
        new_shape = (self.img.shape[1]//dwnscl_factor, # as x,y, not row,columns
                     self.img.shape[0]//dwnscl_factor)

        try:
            dwn_gray_im = cv2.resize(self.img, new_shape)
        except:
            pdb.set_trace()
        # apply blurring
        blur_im = cv2.GaussianBlur(dwn_gray_im, (blr_sigma,blr_sigma),0)
        # normalise between 0 and 255
        blur_im = cv2.normalize(blur_im, None, alpha=0, beta=255,
                                norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
        return blur_im 
Example #5
Source File: object_detection_using_color.py    From Hands-On-Machine-Learning-with-OpenCV-4 with MIT License 6 votes vote down vote up
def capture_histogram(path_of_sample):

    # read the image
    color = cv2.imread(path_of_sample)

    # convert to HSV
    color_hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)

    # compute the histogram
    object_hist = cv2.calcHist([color_hsv],      # image
                               [0, 1],           # channels
                               None,             # no mask
                               [180, 256],       # size of histogram
                               [0, 180, 0, 256]  # channel values
                               )

    # min max normalization
    cv2.normalize(object_hist, object_hist, 0, 255, cv2.NORM_MINMAX)

    return object_hist 
Example #6
Source File: GetMaskParams.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def updateROIs(self):
        #useful for resizing events
        if self.Ifull.size == 0:
            self.twoViews.cleanCanvas()
        else:
            cur = self.ui.tabWidget.currentIndex()
            if cur == self.tab_keys['mask']:
                I1, I2 = self.Ifull, self.Imask
            elif cur == self.tab_keys['bgnd']:
                I1 = self.Ifull
                I2 = np.zeros_like(self.IsubtrB)
                cv2.normalize(self.IsubtrB,I2,0,255,cv2.NORM_MINMAX)
            else:
                I1, I2 = self.Ifull, self.Ifull

            qimage_roi1 = self._numpy2qimage(I1)
            qimage_roi2 = self._numpy2qimage(I2)
            self.twoViews.setPixmap(qimage_roi1, qimage_roi2) 
Example #7
Source File: live_demo.py    From mr_saliency with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, parent, capture, fps=24):
        wx.Panel.__init__(self, parent)
                
        self.capture = capture2
        ret, frame = self.capture.read()


        sal = mr_sal.saliency(frame)
        sal = cv2.resize(sal,(320,240)).astype(sp.uint8)
        sal = cv2.normalize(sal, None, 0, 255, cv2.NORM_MINMAX)
        outsal = cv2.applyColorMap(sal,cv2.COLORMAP_HSV)
        self.bmp = wx.BitmapFromBuffer(320,240, outsal.astype(sp.uint8))

        self.timer = wx.Timer(self)
        self.timer.Start(1000./fps)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_TIMER, self.NextFrame) 
Example #8
Source File: template_matching.py    From dual-fisheye-video-stitching with MIT License 6 votes vote down vote up
def main():
    src = cv2.imread('src.jpg', cv2.IMREAD_GRAYSCALE)
    tpl = cv2.imread('tpl.jpg', cv2.IMREAD_GRAYSCALE)
    result = cv2.matchTemplate(src, tpl, cv2.TM_CCOEFF_NORMED)
    result = cv2.normalize(result, dst=None, alpha=0, beta=1,
                           norm_type=cv2.NORM_MINMAX, dtype=-1)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result)
    matchLoc = maxLoc
    draw1 = cv2.rectangle(
        src, matchLoc, (matchLoc[0] + tpl.shape[1], matchLoc[1] + tpl.shape[0]), 0, 2, 8, 0)
    draw2 = cv2.rectangle(
        result, matchLoc, (matchLoc[0] + tpl.shape[1], matchLoc[1] + tpl.shape[0]), 0, 2, 8, 0)
    cv2.imshow('draw1', draw1)
    cv2.imshow('draw2', draw2)
    cv2.waitKey(0)
    print src.shape
    print tpl.shape
    print result.shape
    print matchLoc 
Example #9
Source File: opticalflow.py    From sign-language with MIT License 6 votes vote down vote up
def flow2colorimage(ar_f_Flow:np.array(float)) -> np.array(int):
    """ translate 1 optical flow (with values from -1.0 to 1.0) to an colorful image
    """

    h, w, c = ar_f_Flow.shape
    if not isinstance(ar_f_Flow[0,0,0], np.float32): 
        warnings.warn("Need to convert flows to float32")
        ar_f_Flow = ar_f_Flow.astype(np.float32)

    ar_n_hsv = np.zeros((h, w, 3), dtype = np.uint8)
    ar_n_hsv[...,1] = 255

    # get colors
    mag, ang = cv2.cartToPolar(ar_f_Flow[..., 0], ar_f_Flow[..., 1])
    ar_n_hsv[...,0] = ang * 180 / np.pi / 2
    ar_n_hsv[...,2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)

    ar_n_bgr = cv2.cvtColor(ar_n_hsv, cv2.COLOR_HSV2BGR)
    return ar_n_bgr 
Example #10
Source File: agent.py    From DRLwithTL with MIT License 6 votes vote down vote up
def get_state(self):
        responses1 = self.client.simGetImages([  # depth visualization image
            airsim.ImageRequest("1", airsim.ImageType.Scene, False,
                                False)])  # scene vision image in uncompressed RGBA array

        response = responses1[0]
        img1d = np.fromstring(response.image_data_uint8, dtype=np.uint8)  # get numpy array
        img_rgba = img1d.reshape(response.height, response.width, 3)
        img = Image.fromarray(img_rgba)
        img_rgb = img.convert('RGB')
        self.iter = self.iter+1
        state = np.asarray(img_rgb)

        state = cv2.resize(state, (self.input_size, self.input_size), cv2.INTER_LINEAR)
        state = cv2.normalize(state, state, 0, 1, cv2.NORM_MINMAX, cv2.CV_32F)
        state_rgb = []
        state_rgb.append(state[:, :, 0:3])
        state_rgb = np.array(state_rgb)
        state_rgb = state_rgb.astype('float32')

        return state_rgb 
Example #11
Source File: smoke_video_dataset_cp.py    From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_frames(file_path, resize_to=224.0):
    # Saved numpy files should be read in with format (time, height, width, channel)
    frames = np.load(file_path)
    t, h, w, c = frames.shape

    # Resize and scale images for the network structure
    #TODO: maybe use opencv to normalize the image
    #frames = cv.normalize(frames, None, alpha=0, beta=1, norm_type=cv.NORM_MINMAX, dtype=cv.CV_32F)
    frames_out = []
    need_resize = False
    if w < resize_to or h < resize_to:
        d = resize_to - min(w, h)
        sc = 1 + d / min(w, h)
        need_resize = True
    for i in range(t):
        img = frames[i, :, :, :]
        if need_resize:
            img = cv.resize(img, dsize=(0, 0), fx=sc, fy=sc)
        img = (img / 255.) * 2 - 1
        frames_out.append(img)
    return np.asarray(frames_out, dtype=np.float32) 
Example #12
Source File: camshift_object_tracker.py    From automl-video-ondevice with Apache License 2.0 6 votes vote down vote up
def calculate_roi_hist(self, frame):
    """Calculates region of interest histogram.

    Args:
      frame: The np.array image frame to calculate ROI histogram for.
    """
    (x, y, w, h) = self.box
    roi = frame[y:y + h, x:x + w]

    hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                       np.array((180., 255., 255.)))
    roi_hist = cv2.calcHist([hsv_roi], [0, 1], mask, [180, 255],
                            [0, 180, 0, 255])
    cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
    self.roi_hist = roi_hist

  # Run this every frame 
Example #13
Source File: imgviewer_conversions.py    From hyperface with MIT License 6 votes vote down vote up
def weights_img_func(key, entry, viewer):
    data = entry['weights']
    assert(data.ndim == 4)
    img_cnt_max = viewer.img_cnt_max[key]

    res_data = list()

    # accumulate to 3 channels image
    for i in six.moves.range(min(data.shape[0], img_cnt_max)):
        img_shape = (3,) + data.shape[2:4]
        accum = np.zeros(img_shape, dtype=data.dtype)
        for ch in six.moves.range(data.shape[1]):
            accum[ch % 3] += data[i][ch]

        # normalize
        img = np.transpose(accum, (1, 2, 0))
        img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)

        width = img.shape[0] * 15
        res_data.append({'img': img, 'width': width})

    return res_data


# ========================= Loss Graph (In a tab page) ======================== 
Example #14
Source File: combine.py    From unet-gan-matting with MIT License 6 votes vote down vote up
def generate_target(object_file, target_name):
    border = 20
    size = [960, 720]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False
    cv2.normalize(foreground, foreground, 0, 255, cv2.NORM_MINMAX)
    foreground = foreground.astype(numpy.uint8)

    ratio = numpy.amin(numpy.divide(
            numpy.subtract(size, [2*border, 2*border]), foreground.shape[0:2]))
    forground_size = numpy.floor(numpy.multiply(foreground.shape[0:2], ratio)).astype(int)
    foreground = cv2.resize(foreground, (forground_size[1], forground_size[0]))
    foreground = image_fill(foreground,size,[0,0,0,0])

    cv2.imwrite(target_name, foreground) 
Example #15
Source File: file_function.py    From gradcam.pytorch with MIT License 6 votes vote down vote up
def resize_and_contrast(in_dir, out_dir, target_size):
    check_and_mkdir(out_dir)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))

    for subdir, dirs, files in os.walk(in_dir):
        for f in files:
            file_path = subdir + os.sep + f
            if (is_image(f)):
                img = cv2.imread(file_path, 0)
                resized_img = cv2.resize(img, (target_size, target_size), interpolation = cv2.INTER_CUBIC)
                class_dir = out_dir + os.sep + file_path.split("/")[-2]
                check_and_mkdir(class_dir)

                file_name = class_dir + os.sep + file_path.split("/")[-1]
                print(file_name)

                norm_image = cv2.normalize(resized_img, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) * 256
                # norm_image = clahe.apply(resized_img)
                cv2.imwrite(file_name, norm_image)

# count the direct one-step sub directories (which will represent the class name) 
Example #16
Source File: utils.py    From BlenderProc with GNU General Public License v3.0 6 votes vote down vote up
def flow_to_rgb(flow):
    """
    Visualizes optical flow in hsv space and converts it to rgb space.
    :param flow: (np.array (h, w, c)) optical flow
    :return: (np.array (h, w, c)) rgb data
    """
    im1 = flow[:, :, 0]
    im2 = flow[:, :, 1]

    h, w = flow.shape[:2]

    # Use Hue, Saturation, Value colour model
    hsv = np.zeros((h, w, 3), dtype=np.float32)
    hsv[..., 1] = 1

    mag, ang = cv2.cartToPolar(im1, im2)
    hsv[..., 0] = ang * 180 / np.pi
    hsv[..., 2] = cv2.normalize(mag, None, 0, 1, cv2.NORM_MINMAX)

    return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) 
Example #17
Source File: event.py    From EVDodgeNet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_frame(self,frame_data):

		# print(frame_data.size)
		frame = np.rec.array(None, dtype=[('value', np.float16),('valid', np.bool_)], shape=(self.height, self.width))
		frame.valid.fill(False)
		frame.value.fill(0.)
		# print(frame.size)

		for datum in np.nditer(frame_data, flags=['zerosize_ok']):
			# print(datum['y'])
			ts_val = datum['ts']
			f_data = frame[datum['y'], datum['x']]
			f_data.value += 1

		img = frame.value/20*255
		img = img.astype('uint8')
		# img = np.piecewise(img, [img <= 0, (img > 0) & (img < 255), img >= 255], [0, lambda x: x, 255])
		# cv2.normalize(img,img,0,255,cv2.NORM_L1)
		cv2.normalize(img,img,0,255,cv2.NORM_MINMAX)
		img = cv2.flip(img, 1)
		img = np.rot90(img)
		# cv2.imshow('img_f', img)
		# cv2.waitKey(0)
		return img 
Example #18
Source File: histogram_custom_visualization.py    From Mastering-OpenCV-4-with-Python with MIT License 5 votes vote down vote up
def plot_hist(hist_items, color):
    """Plots the histogram of a image"""

    # For visualization purposes we add some offset:
    offset_down = 10
    offset_up = 10
    # This will be used for creating the points to visualize (x-coordinates):
    x_values = np.arange(256).reshape(256, 1)
    # Create the canvas where the histogram will be plotted:
    canvas = np.ones((300, 256, 3), dtype="uint8") * 255

    for hist_item, col in zip(hist_items, color):
        # Normalize in the range for proper visualization:
        cv2.normalize(hist_item, hist_item, 0 + offset_down, 300 - offset_up, cv2.NORM_MINMAX)
        # Round the normalized values of the histogram:
        around = np.around(hist_item)
        # Cast the values to int:
        hist = np.int32(around)
        # Create the points using the histogram and the x-coordinates:
        pts = np.column_stack((x_values, hist))
        # Draw the points:
        cv2.polylines(canvas, [pts], False, col, 2)
        # Draw a rectangle:
        cv2.rectangle(canvas, (0, 0), (255, 298), (0, 0, 0), 1)

    # Flip the image in the up/down direction:
    res = np.flipud(canvas)
    return res


# Create the dimensions of the figure and set title: 
Example #19
Source File: stereo_matcher_app.py    From cvcalib with Apache License 2.0 5 votes vote down vote up
def process_output(self, disparity):
        cv8uc = cv2.normalize(disparity, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
        if self.args.preview:
            cv2.imshow("disparity", cv8uc)
            cv2.waitKey(0)
        cv2.imwrite(os.path.join(self.args.folder, self.args.output), cv8uc) 
Example #20
Source File: chessboard.py    From cvcalib with Apache License 2.0 5 votes vote down vote up
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) 
Example #21
Source File: image_utils.py    From vision-ML with MIT License 5 votes vote down vote up
def get_gray_score(binary):
    """
    calculate binary image mean value of normalized array
    :param binary: input binary image
    :return: score between (0-1.0)
    """
    if len(binary.shape) > 2:
        binary = cv2.cvtColor(binary, cv2.COLOR_BGR2GRAY)
    binary = numpy.asarray(binary, dtype=numpy.float32)
    binary_copy = numpy.array(binary, dtype=numpy.float32)
    cv2.normalize(binary, binary_copy, 0, 1, cv2.NORM_MINMAX)
    gray_score = numpy.mean(binary_copy)
    return True if gray_score > 0.5 else False 
Example #22
Source File: combine.py    From unet-gan-matting with MIT License 5 votes vote down vote up
def generate_trimap(object_file, trimap_name):
    border = 20
    size = [960, 720]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False
    alpha = cv2.split(foreground)[3]

    ratio = numpy.amin(numpy.divide(
            numpy.subtract(size, [2*border, 2*border]), alpha.shape[0:2]))
    forground_size = numpy.floor(numpy.multiply(alpha.shape[0:2], ratio)).astype(int)
    alpha = cv2.resize(alpha, (forground_size[1], forground_size[0]))
    alpha = image_fill(alpha,size,[0,0,0,0])

    alpha = alpha.astype(float)
    cv2.normalize(alpha, alpha, 0.0, 1.0, cv2.NORM_MINMAX)

    _, inner_map = cv2.threshold(alpha, 0.999, 255, cv2.THRESH_BINARY)
    _, outer_map = cv2.threshold(alpha, 0.001, 255, cv2.THRESH_BINARY)

    inner_map = cv2.erode(inner_map, numpy.ones((5,5),numpy.uint8), iterations = 3)
    outer_map = cv2.dilate(outer_map, numpy.ones((5,5),numpy.uint8), iterations = 3)

    cv2.imwrite(trimap_name, inner_map + (outer_map - inner_map) /2)

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED) 
Example #23
Source File: test_monkey.py    From ATX with Apache License 2.0 5 votes vote down vote up
def test_features():
    from atx.drivers.android_minicap import AndroidDeviceMinicap
    cv2.namedWindow("preview")
    d = AndroidDeviceMinicap()

    # r, h, c, w = 200, 100, 200, 100
    # track_window = (c, r, w, h)
    # oldimg = cv2.imread('base1.png')
    # roi = oldimg[r:r+h, c:c+w]
    # hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    # mask = cv2.inRange(hsv_roi, 0, 255)
    # roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0,180])
    # cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
    # term_cirt = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,  10, 1)


    while True:
        try:
            w, h = d._screen.shape[:2]
            img = cv2.resize(d._screen, (h/2, w/2))
            cv2.imshow('preview', img)

            hist = cv2.calcHist([img], [0], None, [256], [0,256])
            plt.plot(plt.hist(hist.ravel(), 256))
            plt.show()
            # if img.shape == oldimg.shape:
            #     # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            #     # ret, track_window = cv2.meanShift(hsv, track_window, term_cirt)
            #     # x, y, w, h = track_window
            #     cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
            #     cv2.imshow('preview', img)
            # # cv2.imshow('preview', img)
            cv2.waitKey(1)
        except KeyboardInterrupt:
            break

    cv2.destroyWindow('preview') 
Example #24
Source File: opt_flow.py    From Walk-Assistant with GNU General Public License v3.0 5 votes vote down vote up
def get_direction(self, frame1, frame2, show=False):
        frame1 = cv2.resize(frame1, (self.width, self.height))
        frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
        frame2 = cv2.resize(frame2, (self.width, self.height))
        frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)

        flow = cv2.calcOpticalFlowFarneback(frame1[self.height_start:self.height_end],
                                            frame2[self.height_start:self.height_end], None, 0.5, 3, 15, 1, 5, 1.2, 0)
        flow_avg = np.median(flow, axis=(0, 1))  # [x, y]

        move_x = -1 * flow_avg[0]
        move_y = -1 * flow_avg[1]

        if show:
            hsv = np.zeros((self.height_end - self.height_start, self.width, 3))
            hsv[...,1] = 255
            mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
            hsv[..., 0] = ang * 180 / np.pi / 2
            hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
            bgr = cv2.cvtColor(np.array(hsv).astype(np.uint8), cv2.COLOR_HSV2BGR)

            cv2.imshow('opt_flow', bgr)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                print('User Interrupted')
                exit(1)

        return move_x, move_y 
Example #25
Source File: active_weather.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __sobel_image__(self,image,horizontal):
        """
        apply the sobel operator to a given image on either the vertical or horizontal axis
        basically copied from
        http://stackoverflow.com/questions/10196198/how-to-remove-convexity-defects-in-a-sudoku-square
        :param horizontal:
        :return:
        """
        if horizontal:
            dy = cv2.Sobel(image,cv2.CV_16S,0,2)
            dy = cv2.convertScaleAbs(dy)
            cv2.normalize(dy,dy,0,255,cv2.NORM_MINMAX)
            ret,close = cv2.threshold(dy,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

            kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(10,2))
        else:
            dx = cv2.Sobel(image,cv2.CV_16S,2,0)
            dx = cv2.convertScaleAbs(dx)
            cv2.normalize(dx,dx,0,255,cv2.NORM_MINMAX)
            ret,close = cv2.threshold(dx,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

            kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(2,10))

        close = cv2.morphologyEx(close,cv2.MORPH_CLOSE,kernel)

        return close 
Example #26
Source File: MR.py    From mr_saliency with GNU General Public License v2.0 5 votes vote down vote up
def __MR_fill_superpixel_with_saliency(self,labels,saliency_score):
        sa_img = labels.copy().astype(float)
        for i in range(sp.amax(labels)+1):
            mask = labels == i
            sa_img[mask] = saliency_score[i]
        return cv2.normalize(sa_img,None,0,255,cv2.NORM_MINMAX) 
Example #27
Source File: class_CNN.py    From ALPR_System with Apache License 2.0 5 votes vote down vote up
def read_tensor_from_image(self, image, imageSizeOuput):
    """
    inputs an image and converts to a tensor
    """
    image = cv2.resize(image, dsize=(imageSizeOuput, imageSizeOuput), interpolation = cv2.INTER_CUBIC)
    np_image_data = np.asarray(image)
    np_image_data = cv2.normalize(np_image_data.astype('float'), None, -0.5, .5, cv2.NORM_MINMAX)
    np_final = np.expand_dims(np_image_data,axis=0)
    return np_final 
Example #28
Source File: FingerDetection.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hand_histogram(frame):
    global hand_rect_one_x, hand_rect_one_y

    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    roi = np.zeros([90, 10, 3], dtype=hsv_frame.dtype)

    for i in range(total_rectangle):
        roi[i * 10: i * 10 + 10, 0: 10] = hsv_frame[hand_rect_one_x[i]:hand_rect_one_x[i] + 10,
                                          hand_rect_one_y[i]:hand_rect_one_y[i] + 10]

    hand_hist = cv2.calcHist([roi], [0, 1], None, [180, 256], [0, 180, 0, 256])
    return cv2.normalize(hand_hist, hand_hist, 0, 255, cv2.NORM_MINMAX) 
Example #29
Source File: cvutils.py    From 1ZLAB_PyEspCar with GNU General Public License v3.0 5 votes vote down vote up
def calculate_roi_hist(roi):
    hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)
    
    # calculating object histogram
    roihist = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )
    # normalize histogram and apply backprojection
    cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)

    return roihist 
Example #30
Source File: eval.py    From unet-gan-matting with MIT License 5 votes vote down vote up
def generate_trimap(object_file):
    size = [960/2, 720/2]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False
    print(foreground.shape)
    alpha = cv2.split(foreground)[3]

    ratio = np.amin(np.divide(size, alpha.shape[0:2]))
    forground_size = np.floor(np.multiply(alpha.shape[0:2], ratio)).astype(int)
    alpha = cv2.resize(alpha, (forground_size[1], forground_size[0]))
    alpha = image_fill(alpha,size,[0,0,0,0])

    alpha = alpha.astype(float)
    cv2.normalize(alpha, alpha, 0.0, 1.0, cv2.NORM_MINMAX)

    _, inner_map = cv2.threshold(alpha, 0.9, 255, cv2.THRESH_BINARY)
    _, outer_map = cv2.threshold(alpha, 0.1, 255, cv2.THRESH_BINARY)

    inner_map = cv2.erode(inner_map, np.ones((5,5),np.uint8), iterations = 3)
    outer_map = cv2.dilate(outer_map, np.ones((5,5),np.uint8), iterations = 3)

    return inner_map + (outer_map - inner_map) /2

# Parse Arguments