Python cv2.COLOR_GRAY2BGR Examples

The following are 30 code examples for showing how to use cv2.COLOR_GRAY2BGR(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module cv2 , or try the search function .

Example 1
Project: smashscan   Author: jpnaterer   File: thresholding.py    License: MIT License 9 votes vote down vote up
def contour_filter(self, frame):
        _, contours, _ = cv2.findContours(frame,
            cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        new_frame = np.zeros(frame.shape, np.uint8)
        for i, contour in enumerate(contours):
            c_area = cv2.contourArea(contour)
            if self.contour_min_area <= c_area <= self.contour_max_area:
                mask = np.zeros(frame.shape, np.uint8)
                cv2.drawContours(mask, contours, i, 255, cv2.FILLED)
                mask = cv2.bitwise_and(frame, mask)
                new_frame = cv2.bitwise_or(new_frame, mask)
        frame = new_frame

        if self.contour_disp_flag:
            frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
            cv2.drawContours(frame, contours, -1, (255, 0, 0), 1)

        return frame


    # A number of methods corresponding to the various trackbars available. 
Example 2
Project: tf2-yolo3   Author: akkaze   File: utils.py    License: Apache License 2.0 7 votes vote down vote up
def draw_outputs(img, outputs, class_names=None):
    boxes, objectness, classes = outputs
    #boxes, objectness, classes = boxes[0], objectness[0], classes[0]
    wh = np.flip(img.shape[0:2])
    if img.ndim == 2 or img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    min_wh = np.amin(wh)
    if min_wh <= 100:
        font_size = 0.5
    else:
        font_size = 1
    for i in range(classes.shape[0]):
        x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
        x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
        img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
        img = cv2.putText(img, '{}'.format(int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
                          (0, 0, 255), 1)
    return img 
Example 3
Project: tf2-yolo3   Author: akkaze   File: utils.py    License: Apache License 2.0 7 votes vote down vote up
def draw_labels(x, y, class_names=None):
    img = x.numpy()
    if img.ndim == 2 or img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    boxes, classes = tf.split(y, (4, 1), axis=-1)
    classes = classes[..., 0]
    wh = np.flip(img.shape[0:2])
    min_wh = np.amin(wh)
    if min_wh <= 100:
        font_size = 0.5
    else:
        font_size = 1
    for i in range(len(boxes)):
        x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
        x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
        img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
        if class_names:
            img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
                              (0, 0, 255), 1)
        else:
            img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
    return img 
Example 4
Project: Emojinator   Author: akshaybahadur21   File: Emojinator_V2.py    License: MIT License 6 votes vote down vote up
def blend_transparent(face_img, overlay_t_img):
    # Split out the transparency mask from the colour info
    overlay_img = overlay_t_img[:, :, :3]  # Grab the BRG planes
    overlay_mask = overlay_t_img[:, :, 3:]  # And the alpha plane

    # Again calculate the inverse mask
    background_mask = 255 - overlay_mask

    # Turn the masks into three channel, so we can use them as weights
    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    # Create a masked out face image, and masked out overlay
    # We convert the images to floating point in range 0.0 - 1.0
    face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    # And finally just add them together, and rescale it back to an 8bit integer image
    return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) 
Example 5
Project: OpenCV-Python-Tutorial   Author: makelove   File: digits.py    License: MIT License 6 votes vote down vote up
def evaluate_model(model, digits, samples, labels):
    resp = model.predict(samples)
    err = (labels != resp).mean()
    print('error: %.2f %%' % (err*100))

    confusion = np.zeros((10, 10), np.int32)
    for i, j in zip(labels, resp):
        confusion[i, int(j)] += 1
    print('confusion matrix:')
    print(confusion)
    print()

    vis = []
    for img, flag in zip(digits, resp == labels):
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        if not flag:
            img[...,:2] = 0
        vis.append(img)
    return mosaic(25, vis) 
Example 6
Project: hazymaze   Author: guille0   File: helpers.py    License: Apache License 2.0 6 votes vote down vote up
def blend_non_transparent(sprite, background_img):
    gray_overlay = cv2.cvtColor(background_img, cv2.COLOR_BGR2GRAY)
    overlay_mask = cv2.threshold(gray_overlay, 1, 255, cv2.THRESH_BINARY)[1]

    overlay_mask = cv2.erode(overlay_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
    overlay_mask = cv2.blur(overlay_mask, (3, 3))

    background_mask = 255 - overlay_mask

    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    sprite_part = (sprite * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (background_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    return np.uint8(cv2.addWeighted(sprite_part, 255.0, overlay_part, 255.0, 0.0)) 
Example 7
Project: smashscan   Author: jpnaterer   File: util.py    License: MIT License 6 votes vote down vote up
def get_image_and_mask(img_location, gray_flag):

    # Load image from file with alpha channel (UNCHANGED flag). If an alpha
    # channel does not exist, just return the base image.
    img = cv2.imread(img_location, cv2.IMREAD_UNCHANGED)
    if img.shape[2] <= 3:
        return img, None

    # Create an alpha channel matrix  with values between 0-255. Then
    # threshold the alpha channel to create a binary mask.
    channels = cv2.split(img)
    mask = np.array(channels[3])
    _, mask = cv2.threshold(mask, 250, 255, cv2.THRESH_BINARY)

    # Convert image and mask to grayscale or BGR based on input flag.
    if gray_flag:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    else:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

    return img, mask


# Resize an image and mask based on an input scale ratio. 
Example 8
Project: Traffic-Sign-Detection   Author: hoanglehaithanh   File: classification.py    License: MIT License 6 votes vote down vote up
def evaluate_model(model, data, samples, labels):
    resp = model.predict(samples)
    print(resp)
    err = (labels != resp).mean()
    print('Accuracy: %.2f %%' % ((1 - err)*100))

    confusion = np.zeros((10, 10), np.int32)
    for i, j in zip(labels, resp):
        confusion[int(i), int(j)] += 1
    print('confusion matrix:')
    print(confusion)

    vis = []
    for img, flag in zip(data, resp == labels):
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        if not flag:
            img[...,:2] = 0
        
        vis.append(img)
    return mosaic(16, vis) 
Example 9
Project: imips_open   Author: uzh-rpg   File: sips_system.py    License: GNU General Public License v3.0 6 votes vote down vote up
def render(self, n_max=0, fallback_im=None):
        if self.image_scores is not None:
            im = cv2.applyColorMap((self.image_scores * 255).astype(np.uint8),
                                   cv2.COLORMAP_JET)
        else:
            assert fallback_im is not None
            im = cv2.cvtColor(fallback_im, cv2.COLOR_GRAY2BGR)

        if n_max == 0:
            n_max = self.ips_rc.shape[1]
        for i in range(n_max):
            thickness_relevant_score = \
                np.clip(self.ip_scores[i], 0.2, 0.6) - 0.2
            thickness = int(thickness_relevant_score * 20)
            if type(self.scales) == np.ndarray:
                radius = int(self.scales[i] * 10)
            else:
                radius = 10
            cv2.circle(im, tuple(self.ips_rc[[1, 0], i]),
                       radius, (0, 255, 0), thickness, cv2.LINE_AA)
        return im 
Example 10
Project: imips_open   Author: uzh-rpg   File: evaluate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def renderTrainSample(pair, fps, corr_rc, inl):
    ims = [cv2.cvtColor(i, cv2.COLOR_GRAY2BGR) for i in pair.im]

    rc = system.renderColors()
    for fp, corr, im in zip(fps, corr_rc, ims):
        for i in range(128):
            cv2.circle(im, tuple(fp.ips_rc[[1, 0], i]), 6, tuple(rc[i]), 1,
                       cv2.LINE_AA)
            if inl[i]:
                thck = -1
            else:
                thck = 1
            cv2.circle(im, tuple(corr[[1, 0], i]), 2, tuple(rc[i]), thck,
                       cv2.LINE_AA)

    renderings = [i.render(with_points=False) for i in fps]
    gray_ims = np.concatenate(ims, axis=0)
    rend = np.concatenate(renderings, axis=0)
    full_im = np.concatenate([gray_ims, rend], axis=1)
    outdir = os.path.join(
        'results', 'train_samples', hyperparams.methodEvalString())
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    outfile = os.path.join(outdir, pair.name() + '.png')
    cv2.imwrite(outfile, full_im) 
Example 11
Project: niryo_one_ros   Author: NiryoRobotics   File: image_functions.py    License: GNU General Public License v3.0 6 votes vote down vote up
def concat_imgs(tuple_imgs, axis=1):
    """
    # Concat multiple images along 1 axis
    :param tuple_imgs: tuple of images
    :param axis: 0 means vertically and 1 means horizontally
    :return: Concat image
    """
    new_list_imgs = []
    for image in tuple_imgs:
        if len(image.shape) == 2:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
        new_list_imgs.append(image)

    concat_im = np.concatenate(tuple(new_list_imgs), axis=axis)
    return concat_im


# ROS 
Example 12
Project: OpenCV-3-x-with-Python-By-Example   Author: PacktPublishing   File: 05_cartoonizing.py    License: MIT License 6 votes vote down vote up
def cartoonize_image(img, ksize=5, sketch_mode=False):
    num_repetitions, sigma_color, sigma_space, ds_factor = 10, 5, 7, 4 
    # Convert image to grayscale 
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
 
    # Apply median filter to the grayscale image 
    img_gray = cv2.medianBlur(img_gray, 7) 
 
    # Detect edges in the image and threshold it 
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=ksize) 
    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV) 
 
    # 'mask' is the sketch of the image 
    if sketch_mode: 
        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) 
 
    # Resize the image to a smaller size for faster computation 
    img_small = cv2.resize(img, None, fx=1.0/ds_factor, fy=1.0/ds_factor, interpolation=cv2.INTER_AREA)
 
    # Apply bilateral filter the image multiple times 
    for i in range(num_repetitions): 
        img_small = cv2.bilateralFilter(img_small, ksize, sigma_color, sigma_space) 
 
    img_output = cv2.resize(img_small, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR) 
 
    dst = np.zeros(img_gray.shape) 
 
    # Add the thick boundary lines to the image using 'AND' operator 
    dst = cv2.bitwise_and(img_output, img_output, mask=mask) 
    return dst 
Example 13
Project: Thermal_Image_Analysis   Author: detecttechnologies   File: CThermal.py    License: MIT License 6 votes vote down vote up
def generate_colorbar(self, min_temp=None, max_temp=None, cmap=cv.COLORMAP_JET, height=None):
        if min_temp is None:
            min_temp = self.global_min_temp
        if max_temp is None:
            max_temp = self.global_max_temp
        cb_gray = np.arange(255,0,-1,dtype=np.uint8).reshape((255,1))
        if cmap is not None:
            cb_color = cv.applyColorMap(cb_gray, cmap)
        else:
            cb_color = cv.cvtColor(cb_gray, cv.COLOR_GRAY2BGR)
        for i in range(1,6):
            cb_color = np.concatenate( (cb_color, cb_color), axis=1 )
        
        if height is None:
            append_img = np.zeros( (self.thermal_image.shape[0], cb_color.shape[1]+30, 3), dtype=np.uint8 )
        else:
            append_img = np.zeros( (height, cb_color.shape[1]+30, 3), dtype=np.uint8 )

        append_img[append_img.shape[0]//2-cb_color.shape[0]//2  : append_img.shape[0]//2 - (cb_color.shape[0]//2) + cb_color.shape[0] , 10 : 10 + cb_color.shape[1] ] = cb_color
        cv.putText(append_img, str(min_temp), (5, append_img.shape[0]//2 - (cb_color.shape[0]//2) + cb_color.shape[0] + 30), cv.FONT_HERSHEY_PLAIN, 1, (255,0,0) , 1, 8)
        cv.putText(append_img, str(max_temp), (5, append_img.shape[0]//2-cb_color.shape[0]//2-20) , cv.FONT_HERSHEY_PLAIN, 1, (0,0,255) , 1, 8 )
        return append_img 
Example 14
Project: QuickDraw   Author: uvipen   File: utils.py    License: MIT License 6 votes vote down vote up
def get_overlay(bg_image, fg_image, sizes=(40, 40)):
    fg_image = cv2.resize(fg_image, sizes)
    fg_mask = fg_image[:, :, 3:]
    fg_image = fg_image[:, :, :3]
    bg_mask = 255 - fg_mask
    bg_image = bg_image/255
    fg_image = fg_image/255
    fg_mask = cv2.cvtColor(fg_mask, cv2.COLOR_GRAY2BGR)/255
    bg_mask = cv2.cvtColor(bg_mask, cv2.COLOR_GRAY2BGR)/255
    image = cv2.addWeighted(bg_image*bg_mask, 255, fg_image*fg_mask, 255, 0.).astype(np.uint8)
    return image





# if __name__ == '__main__':
#     images = get_images("../images", ["apple", "star"])
#     print(images[0].shape)
#     print(np.max(images[0])) 
Example 15
Project: sips2_open   Author: uzh-rpg   File: system.py    License: GNU General Public License v3.0 6 votes vote down vote up
def render(self, n_max=0, fallback_im=None):
        if self.image_scores is not None:
            im = cv2.applyColorMap((self.image_scores * 255).astype(np.uint8),
                                   cv2.COLORMAP_JET)
        else:
            assert fallback_im is not None
            im = cv2.cvtColor(fallback_im, cv2.COLOR_GRAY2BGR)

        if n_max == 0:
            n_max = self.ips_rc.shape[1]
        for i in range(n_max):
            thickness_relevant_score = \
                np.clip(self.ip_scores[i], 0.2, 0.6) - 0.2
            thickness = int(thickness_relevant_score * 20)
            if type(self.scales) == np.ndarray:
                radius = int(self.scales[i] * 10)
            else:
                radius = 10
            cv2.circle(im, tuple(self.ips_rc[[1, 0], i]),
                       radius, (0, 255, 0), thickness, cv2.LINE_AA)
        return im 
Example 16
Project: songoku   Author: guille0   File: helpers.py    License: MIT License 6 votes vote down vote up
def blend_non_transparent(face_img, overlay_img):
    # Let's find a mask covering all the non-black (foreground) pixels
    # NB: We need to do this on grayscale version of the image
    gray_overlay = cv2.cvtColor(overlay_img, cv2.COLOR_BGR2GRAY)
    overlay_mask = cv2.threshold(gray_overlay, 1, 255, cv2.THRESH_BINARY)[1]

    # Let's shrink and blur it a little to make the transitions smoother...
    overlay_mask = cv2.erode(overlay_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
    overlay_mask = cv2.blur(overlay_mask, (3, 3))

    # And the inverse mask, that covers all the black (background) pixels
    background_mask = 255 - overlay_mask

    # Turn the masks into three channel, so we can use them as weights
    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    # Create a masked out face image, and masked out overlay
    # We convert the images to floating point in range 0.0 - 1.0
    face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    # And finally just add them together, and rescale it back to an 8bit integer image
    return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) 
Example 17
Project: KAIR   Author: cszn   File: utils_image.py    License: MIT License 5 votes vote down vote up
def channel_convert(in_c, tar_type, img_list):
    # conversion among BGR, gray and y
    if in_c == 3 and tar_type == 'gray':  # BGR to gray
        gray_list = [cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for img in img_list]
        return [np.expand_dims(img, axis=2) for img in gray_list]
    elif in_c == 3 and tar_type == 'y':  # BGR to y
        y_list = [bgr2ycbcr(img, only_y=True) for img in img_list]
        return [np.expand_dims(img, axis=2) for img in y_list]
    elif in_c == 1 and tar_type == 'RGB':  # gray/y to BGR
        return [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_list]
    else:
        return img_list 
Example 18
Project: OpenCV-Python-Tutorial   Author: makelove   File: mouse_and_match.py    License: MIT License 5 votes vote down vote up
def onmouse(event, x, y, flags, param):
    global drag_start, sel
    if event == cv2.EVENT_LBUTTONDOWN:
        drag_start = x, y
        sel = 0,0,0,0
    elif event == cv2.EVENT_LBUTTONUP:
        if sel[2] > sel[0] and sel[3] > sel[1]:
            patch = gray[sel[1]:sel[3],sel[0]:sel[2]]
            result = cv2.matchTemplate(gray,patch,cv2.TM_CCOEFF_NORMED)
            result = np.abs(result)**3
            val, result = cv2.threshold(result, 0.01, 0, cv2.THRESH_TOZERO)
            result8 = cv2.normalize(result,None,0,255,cv2.NORM_MINMAX,cv2.CV_8U)
            cv2.imshow("result", result8)
        drag_start = None
    elif drag_start:
        #print flags
        if flags & cv2.EVENT_FLAG_LBUTTON:
            minpos = min(drag_start[0], x), min(drag_start[1], y)
            maxpos = max(drag_start[0], x), max(drag_start[1], y)
            sel = minpos[0], minpos[1], maxpos[0], maxpos[1]
            img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
            cv2.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)
            cv2.imshow("gray", img)
        else:
            print("selection is complete")
            drag_start = None 
Example 19
Project: OpenCV-Python-Tutorial   Author: makelove   File: opt_flow.py    License: MIT License 5 votes vote down vote up
def draw_flow(img, flow, step=16):
    h, w = img.shape[:2]
    y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1).astype(int)
    fx, fy = flow[y,x].T
    lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)
    lines = np.int32(lines + 0.5)
    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.polylines(vis, lines, 0, (0, 255, 0))
    for (x1, y1), (x2, y2) in lines:
        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
    return vis 
Example 20
Project: OpenCV-Python-Tutorial   Author: makelove   File: code.py    License: MIT License 5 votes vote down vote up
def drawlines(img1, img2, lines, pts1, pts2):
    ''' img1 - image on which we draw the epilines for the points in img2
        lines - corresponding epilines '''
    r, c = img1.shape
    img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)
    img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)
    for r, pt1, pt2 in zip(lines, pts1, pts2):
        color = tuple(np.random.randint(0, 255, 3).tolist())
        x0, y0 = map(int, [0, -r[2] / r[1]])
        x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1]])
        img1 = cv2.line(img1, (x0, y0), (x1, y1), color, 1)
        img1 = cv2.circle(img1, tuple(pt1), 5, color, -1)
        img2 = cv2.circle(img2, tuple(pt2), 5, color, -1)
    return img1, img2 
Example 21
Project: opencv-engine   Author: thumbor   File: engine_cv3.py    License: MIT License 5 votes vote down vote up
def image_data_as_rgb(self, update_image=True):
        if self.image_channels == 4:
            mode = 'BGRA'
        elif self.image_channels == 3:
            mode = 'BGR'
        else:
            mode = 'BGR'
            rgb_copy = np.zeros((self.size[1], self.size[0], 3), self.image.dtype)
            cv2.cvtColor(self.image, cv2.COLOR_GRAY2BGR, rgb_copy)
            self.image = rgb_copy
        return mode, self.image.tostring() 
Example 22
Project: SolveSudoku   Author: aakashjhawar   File: SudokuExtractor.py    License: MIT License 5 votes vote down vote up
def convert_when_colour(colour, img):
	"""Dynamically converts an image to colour if the input colour is a tuple and the image is grayscale."""
	if len(colour) == 3:
		if len(img.shape) == 2:
			img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
		elif img.shape[2] == 1:
			img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
	return img 
Example 23
Project: SolveSudoku   Author: aakashjhawar   File: SudokuExtractor.py    License: MIT License 5 votes vote down vote up
def display_points(in_img, points, radius=5, colour=(0, 0, 255)):
	"""Draws circular points on an image."""
	img = in_img.copy()

	# Dynamically change to a colour image if necessary
	if len(colour) == 3:
		if len(img.shape) == 2:
			img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
		elif img.shape[2] == 1:
			img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

	for point in points:
		img = cv2.circle(img, tuple(int(x) for x in point), radius, colour, -1)
	show_image(img)
	return img 
Example 24
Project: keras-image-segmentation   Author: dhkim0225   File: callbacks.py    License: MIT License 5 votes vote down vote up
def train_visualization_seg(self, model, epoch, path):
        # image_name_list = sorted(glob(os.path.join(self.flag.data_path,'val/IMAGE/*/frankfurt_000000_014480_leftImg8bit.png')))
        # print (image_name_list)

        image_name = path #'./result/frankfurt_000000_014480_leftImg8bit.png'
        image_height = self.flag.image_height
        image_width = self.flag.image_width
        
        imgInput = cv2.imread(image_name, self.flag.color_mode)
        imgInput = cv2.cvtColor(imgInput, cv2.COLOR_BGR2RGB)
        output_path = self.flag.output_dir
        input_data = imgInput.reshape((1,image_height,image_width,self.flag.color_mode*2+1))

        t_start = cv2.getTickCount()
        result = model.predict(input_data, 1)
        t_total = (cv2.getTickCount() - t_start) / cv2.getTickFrequency() * 1000
        print ("[*] Predict Time: %.3f ms"%t_total)
        
        imgMask = (result[0]*255).astype(np.uint8)
        imgShow = cv2.cvtColor(imgInput, cv2.COLOR_RGB2BGR).copy()
        #cv2.cvtColor(imgInput, cv2.COLOR_GRAY2BGR)
        # imgMaskColor = cv2.applyColorMap(imgMask, cv2.COLORMAP_JET)
        imgMaskColor = imgMask
        imgShow = cv2.addWeighted(imgShow, 0.5, imgMaskColor, 0.6, 0.0)
        output_path = os.path.join(self.flag.output_dir, '%04d_'%epoch+os.path.basename(image_name))
        mask_path = os.path.join(self.flag.output_dir, 'mask_%04d_'%epoch+os.path.basename(image_name))
        cv2.imwrite(output_path, imgShow)
        cv2.imwrite(mask_path, imgMaskColor)
        # print "SAVE:[%s]"%output_path
        # cv2.imwrite(os.path.join(output_path, 'img%04d.png'%epoch), imgShow)
        # cv2.namedWindow("show", 0)
        # cv2.resizeWindow("show", 800, 800)
        # cv2.imshow("show", imgShow)
        # cv2.waitKey(1) 
Example 25
Project: MachineLearning   Author: mengli   File: opt_flow.py    License: Apache License 2.0 5 votes vote down vote up
def draw_flow(img, flow, step=16):
    h, w = img.shape[:2]
    y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1).astype(int)
    fx, fy = flow[y, x].T
    lines = np.vstack([x, y, x + fx, y + fy]).T.reshape(-1, 2, 2)
    lines = np.int32(lines + 0.5)
    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.polylines(vis, lines, 0, (0, 255, 0))
    for (x1, y1), (x2, y2) in lines:
        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
    return vis 
Example 26
Project: ALPR-Indonesia   Author: muchlisinadi   File: DetectChars.py    License: MIT License 5 votes vote down vote up
def recognizeCharsInPlate(imgThresh, listOfMatchingChars):
    strChars = ""               # this will be the return value, the chars in the lic plate

    height, width = imgThresh.shape

    imgThreshColor = np.zeros((height, width, 3), np.uint8)

    listOfMatchingChars.sort(key = lambda matchingChar: matchingChar.intCenterX)        # sort chars from left to right

    cv2.cvtColor(imgThresh, cv2.COLOR_GRAY2BGR, imgThreshColor)                     # make color version of threshold image so we can draw contours in color on it

    for currentChar in listOfMatchingChars:                                         # for each char in plate
        pt1 = (currentChar.intBoundingRectX, currentChar.intBoundingRectY)
        pt2 = ((currentChar.intBoundingRectX + currentChar.intBoundingRectWidth), (currentChar.intBoundingRectY + currentChar.intBoundingRectHeight))

        cv2.rectangle(imgThreshColor, pt1, pt2, Main.SCALAR_GREEN, 2)           # draw green box around the char

                # crop char out of threshold image
        imgROI = imgThresh[currentChar.intBoundingRectY : currentChar.intBoundingRectY + currentChar.intBoundingRectHeight,
                           currentChar.intBoundingRectX : currentChar.intBoundingRectX + currentChar.intBoundingRectWidth]

        imgROIResized = cv2.resize(imgROI, (RESIZED_CHAR_IMAGE_WIDTH, RESIZED_CHAR_IMAGE_HEIGHT))           # resize image, this is necessary for char recognition

        npaROIResized = imgROIResized.reshape((1, RESIZED_CHAR_IMAGE_WIDTH * RESIZED_CHAR_IMAGE_HEIGHT))        # flatten image into 1d numpy array

        npaROIResized = np.float32(npaROIResized)               # convert from 1d numpy array of ints to 1d numpy array of floats

        retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k = 1)              # finally we can call findNearest !!!

        strCurrentChar = str(chr(int(npaResults[0][0])))            # get character from results

        strChars = strChars + strCurrentChar                        # append current char to full string

    # end for

    return strChars
# end function 
Example 27
Project: openseg.pytorch   Author: openseg-group   File: image_helper.py    License: MIT License 5 votes vote down vote up
def gray2bgr(img):
        """Convert a grayscale image to BGR image.

        Args:
            img (ndarray or str): The input image.

        Returns:
            ndarray: The converted BGR image.
        """
        img = img[..., None] if img.ndim == 2 else img
        out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        return out_img 
Example 28
Project: BasicSR   Author: xinntao   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def channel_convert(in_c, tar_type, img_list):
    # conversion among BGR, gray and y
    if in_c == 3 and tar_type == 'gray':  # BGR to gray
        gray_list = [cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for img in img_list]
        return [np.expand_dims(img, axis=2) for img in gray_list]
    elif in_c == 3 and tar_type == 'y':  # BGR to y
        y_list = [bgr2ycbcr(img, only_y=True) for img in img_list]
        return [np.expand_dims(img, axis=2) for img in y_list]
    elif in_c == 1 and tar_type == 'RGB':  # gray/y to BGR
        return [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_list]
    else:
        return img_list 
Example 29
def convert_grey_to_bgr(image):
    return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) 
Example 30
Project: TextSnake.pytorch   Author: princewang1994   File: visualize.py    License: MIT License 5 votes vote down vote up
def visualize_detection(image, contours, tr=None, tcl=None):
    image_show = image.copy()
    image_show = np.ascontiguousarray(image_show[:, :, ::-1])
    image_show = cv2.polylines(image_show, contours, True, (0, 0, 255), 3)

    if (tr is not None) and (tcl is not None):
        tr = (tr > cfg.tr_thresh).astype(np.uint8)
        tcl = (tcl > cfg.tcl_thresh).astype(np.uint8)
        tr = cv2.cvtColor(tr * 255, cv2.COLOR_GRAY2BGR)
        tcl = cv2.cvtColor(tcl * 255, cv2.COLOR_GRAY2BGR)
        image_show = np.concatenate([image_show, tr, tcl], axis=1)
        return image_show
    else:
        return image_show