示例#1
0
def sharpen(imgs_to_process, index):
    image = imgs_to_process[index]
    result_1 = unsharp_mask(image, radius=1, amount=1)
    result_2 = unsharp_mask(image, radius=5, amount=2)
    result_3 = unsharp_mask(image, radius=20, amount=1)

    fig, axes = plt.subplots(nrows=2,
                             ncols=2,
                             sharex=True,
                             sharey=True,
                             figsize=(10, 10))
    ax = axes.ravel()

    ax[0].imshow(image, cmap=plt.cm.gray)
    ax[0].set_title('Original image')
    ax[1].imshow(result_1, cmap=plt.cm.gray)
    ax[1].set_title('Enhanced image, radius=1, amount=1.0')
    ax[2].imshow(result_2, cmap=plt.cm.gray)
    ax[2].set_title('Enhanced image, radius=5, amount=2.0')
    ax[3].imshow(result_3, cmap=plt.cm.gray)
    ax[3].set_title('Enhanced image, radius=20, amount=1.0')

    for a in ax:
        a.axis('off')
    fig.tight_layout()
    plt.show()
示例#2
0
def unsharp(dst) :   
    filename = 'static/image/savedImage.jpg'
    result_1 = unsharp_mask(dst, radius=1, amount=1)
    result_2 = unsharp_mask(dst, radius=5, amount=1)
    result_3 = unsharp_mask(dst, radius=10, amount=1)
    result_4 = unsharp_mask(dst, radius=15, amount=1)
    result_5 = unsharp_mask(dst, radius=20, amount=1)  
    io.imsave(filename.replace('.jpg', '_1.jpg'), result_1) 
    io.imsave(filename.replace('.jpg', '_2.jpg'), result_2) 
    io.imsave(filename.replace('.jpg', '_3.jpg'), result_3) 
    io.imsave(filename.replace('.jpg', '_4.jpg'), result_4) 
    io.imsave(filename.replace('.jpg', '_5.jpg'), result_5) 
def sharpen_anat(in_file, save_dir):
    ### Load brain ###
    #file = os.path.join(directory, 'anat_red_clean.nii')
    brain = load_numpy_brain(in_file)

    # renormalize to .3-.7
    a = .3
    b = .7
    brain_input = a + (brain) * (b - a)

    # sharpen
    brain_sharp = unsharp_mask(brain_input, radius=3, amount=7)

    # make background nan
    brain_copy = brain_sharp.copy()
    brain_copy[np.where(brain_input < .31)] = np.nan

    # renormalize via quantile
    brain_out = quantile_transform(brain_copy.flatten().reshape(-1, 1),
                                   n_quantiles=500,
                                   random_state=0,
                                   copy=True)
    brain_out = brain_out.reshape(brain.shape)
    np.nan_to_num(brain_out, copy=False)

    ### Save brain ###
    fname = in_file.split('/')[-1].split('.')[0]
    save_file = os.path.join(save_dir, f'{fname}_sharp.nii')
    aff = np.eye(4)
    img = nib.Nifti1Image(brain_out, aff)
    img.to_filename(save_file)
示例#4
0
def random_sharpen(image_array: ndarray):
    # 随机锐化
    random_radius = random.uniform(1, 20)
    random_amount = random.uniform(1, 5)
    return unsharp_mask(image_array,
                        radius=random_radius,
                        amount=random_amount)
示例#5
0
def unsharp(img_np, radius=5, amount=2):
    """unsharp"""
    # img_np_gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)

    img_np_gb = cv2.GaussianBlur(img_np, (3, 3), 0)
    img_np_um = unsharp_mask(img_np_gb, radius=radius, amount=amount).astype(np.float32) * 255

    return img_np_um.astype(np.uint8)
示例#6
0
def sharp(imagePath, outputPath):
    warnings.filterwarnings("ignore")
    imagePath = "" + imagePath
    color = io.imread(imagePath)
    sharp = unsharp_mask(color, radius=5, amount=1)
    sharp_uint8 = img_as_ubyte(sharp)
    imsave('' + outputPath, sharp_uint8)
    sharp_uint8
def localize(plate_area, video_type, original_car_frame, callback, schoolID):

    plate_copy = plate_area.copy()

    img = rgb2gray(plate_area)
    sharpened = unsharp_mask(img, radius=3, amount=20)

    thresh_value = threshold_otsu(sharpened)
    thresh = thresh_value < sharpened

    labels = measure.label(thresh)

    # different videos have different 'requirements' for a plate object

    plate_dimensions_dictionary = {
        'normal': (.015*img.shape[0], .4*img.shape[0], .015*img.shape[1], .4*img.shape[1]),
        'garage': (.2*img.shape[0], .8*img.shape[0], .05*img.shape[1], .2*img.shape[1]),
        'angles': (.2*img.shape[0], .9*img.shape[0], .1*img.shape[1], .9*img.shape[1])      # angles has a much wider range of angles, widths, and heights
    }   

    plate_dimensions = plate_dimensions_dictionary[video_type]
    min_height, max_height, min_width, max_width = plate_dimensions
    
    threads = []

    for region in regionprops(labels):

        # eliminate areas that are just noise
        if region.area < 100:
            continue

        y0, x0, y1, x1 = region.bbox

        region_height = y1 - y0 
        region_width = x1 - x0 
        
        # a license plate must be wider than it is tall 
        if region_height > region_width:
            continue

        if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width:

            # callback(x0, y0, region_width, region_height)

            rect_border = patches.Rectangle((x0, y0), x1 - x0, y1 - y0, edgecolor="blue", linewidth=2, fill=False)
            # ax[4].add_patch(rect_border)
            
            # plate = plate_copy[y0:y1, x0:x1]
            # imsave('./plate_frames/plate{}.png'.format(time.now()), img_as_ubyte(plate))

            roi = plate_copy[y0: y1, x0: x1]
            points = [(x0, y0), (x1, y0), (x0, y1), (x1, y1)]

            # create a new thread for the current detected plate to speed up performance 
            with concurrent.futures.ThreadPoolExecutor() as executor: 
                f1 = executor.submit(localizeThread, roi, original_car_frame, schoolID, alertNewLicensePlate)
                print(f1.result() if len(f1.result()) == 7)
示例#8
0
def test_unsharp_masking_output_type_and_shape(
        radius, amount, shape, multichannel, dtype, offset, preserve):
    array = np.random.random(shape)
    array = ((array + offset) * 128).astype(dtype)
    if (preserve is False) and (dtype in [np.float32, np.float64]):
        array /= max(np.abs(array).max(), 1.0)
    output = unsharp_mask(array, radius, amount, multichannel, preserve)
    assert output.dtype in [np.float32, np.float64]
    assert output.shape == shape
def test_unsharp_masking_output_type_and_shape(
        radius, amount, shape, multichannel, dtype, offset, preserve):
    array = np.random.random(shape)
    array = ((array + offset) * 128).astype(dtype)
    if (preserve is False) and (dtype in [np.float32, np.float64]):
        array /= max(np.abs(array).max(), 1.0)
    with expected_warnings([r'precision|\A\Z']):
        output = unsharp_mask(array, radius, amount, multichannel, preserve)
    assert output.dtype in [np.float32, np.float64]
    assert output.shape == shape
def test_unsharp_masking_with_different_radii(radius, shape,
                                              multichannel, preserve):
    amount = 1.0
    dtype = np.float64
    array = (np.random.random(shape) * 96).astype(dtype)
    if preserve is False:
        array /= max(np.abs(array).max(), 1.0)
    output = unsharp_mask(array, radius, amount, multichannel, preserve)
    assert output.dtype in [np.float32, np.float64]
    assert output.shape == shape
示例#11
0
    def __call__(self, sample):
        image, mask = sample

        if np.random.rand() > self.prob:
            return image, mask

        amount = np.random.uniform(low=self.sharping_magnitude[0],
                                   high=self.sharping_magnitude[1])
        image = unsharp_mask(image, amount=amount)

        return image, mask
示例#12
0
def unsharp_masking(image):
    #image = imageGlobal
    result_1 = unsharp_mask(image, radius=1, amount=1)
    result_2 = unsharp_mask(image, radius=5, amount=2)
    result_3 = unsharp_mask(image, radius=20, amount=1)

    fig, axes = plt.subplots(nrows=1, ncols=2,
                             sharex=True, sharey=True, figsize=(10, 10))
    ax = axes.ravel()

    ax[0].imshow(image, cmap=plt.cm.gray)
    ax[0].set_title('Original image')

    ax[1].imshow(result_3, cmap=plt.cm.gray)
    ax[1].set_title('Enhanced image, radius=20, amount=1.0')

    for a in ax:
        a.axis('off')
    fig.tight_layout()
    plt.show()
def KendiFiltrem():
    global filterimage
    eroded = morphology.erosion(resim,
                                selem=None,
                                out=None,
                                shift_x=False,
                                shift_y=False)
    imgFilter6 = filters.median(eroded)
    imgFilter2 = filters.unsharp_mask(imgFilter6, radius=1.0, amount=1.0)
    rotateimg = rotate(imgFilter2, 15)
    filterimage = rotateimg
    io.imshow(rotateimg)
    io.show()
示例#14
0
def label_dapi(array):
    gamma_corrected = exposure.adjust_gamma(array, 0.95, 0.8)
    dapi_filter = lambda x: ((x[2] > 0.7))
    unsharp_masked = filters.unsharp_mask(gamma_corrected, radius=5, amount=20, multichannel=True)
    match_arr = np.zeros((unsharp_masked.shape[0], unsharp_masked.shape[1]))
    for i in range(len(unsharp_masked)):
            for j in range(len(unsharp_masked[i])):
                    if dapi_filter(unsharp_masked[i][j]):
                        unsharp_masked[i][j] = np.array([1, 1, 1], dtype=np.uint8)
                        match_arr[i, j] = 1
    labelled = measure.label(binary_erosion(match_arr))
    labelling_final = measure.label(remove_small_objects(labelled, 15))
    return labelling_final
示例#15
0
def unsharp_mask(arr1d):
    """
    TypeError: ndarray() missing required argument 'shape' (pos 1)
    :param arr1d:
    :return:
    """
    import skimage.filters as sf
    thresh = sf.unsharp_mask(arr1d,
                             radius=1.0,
                             amount=1.0,
                             multichannel=False,
                             preserve_range=False)
    return thresh
示例#16
0
def sharpen(img, radius=5, amount=3, override=False):
    """
        Mathematically the following occurs..
        sharp_img = gray_img + amount * (gray_img - Gaussian(gray_img, kernel_raidus))
        Tweak the radius and amount according to image size
    """

    img_height = img.shape[0]
    if not override:
        print("overriding")
        radius, amount = int(math.ceil(img_height / 2.0)), int(math.ceil(img_height / 3.0))

    sharp_img = (unsharp_mask(to_gray(img), radius, amount) * 255).astype(np.uint8)
    return sharp_img
示例#17
0
def run(img):
  
    if len(img.shape) > 2 and img.shape[2] == 4:
        img = color.rgba2rgb(img)
    if len(img.shape) == 2:
        img = color.gray2rgb(img)

    med = median(img, ball(4))
    usm = unsharp_mask(med, radius=2, amount=1)
    eqh = adjust_gamma(usm, gamma=2)

    mask = color.rgb2gray(io.imread(os.path.dirname(os.path.abspath(__file__)) + './barcode.png'))
    mask = resize(mask, eqh.shape)

    return to_base64(eqh * mask)
示例#18
0
def unsharp_masking(img, do_plt=True):
    img_out = unsharp_mask(img, radius=5)

    # img_blur = cv2.GaussianBlur(img, (5, 5), 0)
    # img_out = cv2.addWeighted(img, 2, img_blur, -1, 0)
    if do_plt:
        plt.figure()
        plt.subplot(121)
        plt.imshow(img, cmap='gray')
        plt.title('origin image')
        plt.subplot(122)
        plt.title('enhanced image')
        plt.imshow(img_out, cmap='gray')
        plt.show()
    return img
def test_unsharp_masking_with_different_ranges(shape, offset,
                                               multichannel, preserve):
    radius = 2.0
    amount = 1.0
    dtype = np.int16
    array = (np.random.random(shape) * 5 + offset).astype(dtype)
    negative = np.any(array < 0)
    output = unsharp_mask(array, radius, amount, multichannel, preserve)
    if preserve is False:
        assert np.any(output <= 1)
        assert np.any(output >= -1)
        if negative is False:
            assert np.any(output >= 0)
    assert output.dtype in [np.float32, np.float64]
    assert output.shape == shape
示例#20
0
def test_unsharp_masking_with_different_ranges_deprecated(
        shape, offset, multichannel, preserve):
    radius = 2.0
    amount = 1.0
    dtype = np.int16
    array = (np.random.random(shape) * 5 + offset).astype(dtype)
    negative = np.any(array < 0)
    with expected_warnings(["`multichannel` is a deprecated argument"]):
        output = unsharp_mask(array,
                              radius,
                              amount,
                              multichannel=multichannel,
                              preserve_range=preserve)
    if preserve is False:
        assert np.any(output <= 1)
        assert np.any(output >= -1)
        if negative is False:
            assert np.any(output >= 0)
    assert output.dtype in [np.float32, np.float64]
    assert output.shape == shape

    # providing multichannel positionally also raises a warning
    with expected_warnings(["Providing the `multichannel`"]):
        output = unsharp_mask(array, radius, amount, multichannel, preserve)
示例#21
0
 def block(img):
     # FIXME: grid searchowac ten fragment?
     """ agressive
     from skimage.morphology import disk
     from skimage.filters import rank
     selem = disk(30)
     img = rank.equalize(img, selem=selem)
     img = exposure.equalize_adapthist(img)
     img = exposure.adjust_gamma(img)
     img = unsharp_mask(img, radius=5, amount=2)
     img = ndimage.uniform_filter(img, size=4)"""
     img = exposure.equalize_adapthist(img)
     img = exposure.adjust_gamma(img)
     img = unsharp_mask(img, radius=3, amount=2)
     img = ndimage.uniform_filter(img, size=2)
     return (img * 255).astype(np.uint8)
示例#22
0
def test_unsharp_masking_dtypes(shape, channel_axis, preserve, dtype):
    radius = 2.0
    amount = 1.0
    array = (np.random.random(shape) * 10).astype(dtype, copy=False)
    negative = np.any(array < 0)
    output = unsharp_mask(array,
                          radius,
                          amount,
                          preserve_range=preserve,
                          channel_axis=channel_axis)
    if preserve is False:
        assert np.any(output <= 1)
        assert np.any(output >= -1)
        if negative is False:
            assert np.any(output >= 0)
    assert output.dtype == _supported_float_type(dtype)
    assert output.shape == shape
示例#23
0
    enhanced image = original + amount * (original - blurred)

The blurring step could use any image filter method, e.g. median filter,
but traditionally a gaussian filter is used. The radius parameter in the
unsharp masking filter refers to the sigma parameter of the gaussian filter.

This example shows the effect of different radius and amount parameters.

"""

from skimage import data
from skimage.filters import unsharp_mask
import matplotlib.pyplot as plt

image = data.moon()
result_1 = unsharp_mask(image, radius=1, amount=1)
result_2 = unsharp_mask(image, radius=5, amount=2)
result_3 = unsharp_mask(image, radius=20, amount=1)

fig, axes = plt.subplots(nrows=2, ncols=2,
                         sharex=True, sharey=True, figsize=(10, 10))
ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title('Original image')
ax[1].imshow(result_1, cmap=plt.cm.gray)
ax[1].set_title('Enhanced image, radius=1, amount=1.0')
ax[2].imshow(result_2, cmap=plt.cm.gray)
ax[2].set_title('Enhanced image, radius=5, amount=2.0')
ax[3].imshow(result_3, cmap=plt.cm.gray)
ax[3].set_title('Enhanced image, radius=20, amount=1.0')