Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def run_to_task():
import general_utils
from general_utils import RuntimeDeterminedEnviromentVars
tf.logging.set_verbosity(tf.logging.ERROR)
args = parser.parse_args()
img = load_raw_image_center_crop( args.im_name )
img = skimage.img_as_float(img)
scipy.misc.toimage(np.squeeze(img), cmin=0.0, cmax=1.0).save(args.im_name)
task = args.task
if task not in list_of_tasks:
raise ValueError('Task not supported')
cfg = generate_cfg(task)
# Since we observe that areas with pixel values closes to either 0 or 1 sometimes overflows, we clip pixels value
low_sat_tasks = 'autoencoder curvature denoise edge2d edge3d \
keypoint2d keypoint3d \
reshade rgb2depth rgb2mist rgb2sfnorm \
segment25d segment2d room_layout'.split()
if task in low_sat_tasks:
cfg['input_preprocessing_fn'] = load_ops.resize_rescale_image_low_sat
def generate_samples(path, outdir):
imgdb = np.array(io.imread_collection('data/cnn_printed_50px/*.png'))
for i, im1 in enumerate(imgdb):
im2 = normal(100, 1, (50, 50))
im2 /= im2.max()
im = cv2.addWeighted(img_as_float(im1), 0.7,
img_as_float(im2), 0.3, 0.0)
io.imsave("data/cnn_printed_50px_new/im(" +
str(i)+".png", img_as_float(im))
if label == 1:
votes_printed = votes_printed + 1
step_h = step_h + 30
if votes_hw > votes_printed:
mask[y:y+h,x:x+w][np.where((mask[y:y+h,x:x+w] == [255,255,255]).all(axis = 2))] = [255,0,0]
cv2.rectangle(cvim, (x, y), (x + w, y + h),
(255, 0, 0), 2, 4)
elif votes_hw < votes_printed:
mask[y:y+h,x:x+w][np.where((mask[y:y+h,x:x+w] == [255,255,255]).all(axis = 2))] = [0,255,0]
cv2.rectangle(cvim, (x, y), (x + w, y + h),
(0, 255, 0), 2, 4)
mask[np.where((mask == [0,0,0]).all(axis = 2))] = [0,0,255]
mask[np.where((mask == [255,255,255]).all(axis = 2))] = [0,0,255]
io.imsave("res/res_"+str(im_index)+"_"+classifier+"_"+".png", img_as_float(cvim))
io.imsave("training/mask_"+str(im_index)+"_"+classifier+"_"+".png", img_as_float(mask))
print("saved image"+str(im_index)+"/"+str(len(img_collection)))
if __name__ == "__main__":
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
Notes
-----
The kernel was constructed using the 5-tap weights from [1].
References
----------
.. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete
multidimensional signals", IEEE Transactions on Image Processing
13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819`
.. [2] Farid, H. and Simoncelli, E. P. "Optimally rotation-equivariant
directional derivative kernels", In: 7th International Conference on
Computer Analysis of Images and Patterns, Kiel, Germany. Sep, 1997.
"""
check_nD(image, 2)
image = img_as_float(image)
result = convolve(image, HFARID_WEIGHTS)
return _mask_filter_result(result, mask)
Stretch the image intensity to saturate the top and bottom
quantiles given.
mask : array of bool, same shape as im, optional
Only stretch the image intensity where `mask` is ``True``.
Returns
-------
imc : np.ndarray of float, same shape as `im`
The corrected image.
See Also
--------
`correct_multiimage_illumination`
"""
if im.dtype != np.float:
imc = skimage.img_as_float(im)
else:
imc = im.copy()
imc /= illum
lim = stretch_quantile
imc = stretchlim(imc, lim, 1-lim, mask)
return imc
### Example script showing how to perform a 2D Total-Variation filtering with proxTV
import prox_tv as ptv
import matplotlib.pyplot as plt
import time
import skimage as ski
from skimage import io, color, util
import os
# Load image
here = os.path.dirname(os.path.abspath(__file__))
X = io.imread(here + '/colors.png')
X = ski.img_as_float(X)
X = color.rgb2gray(X)
# Introduce noise
noiseLevel = 0.01
N = util.random_noise(X, mode='speckle', var=noiseLevel)
# Filter using 2D TV-L1
lam=0.15;
print('Filtering image with 2D TV-L1...')
start = time.time()
F = ptv.tv1_2d(N, lam)
end = time.time()
print('Elapsed time ' + str(end-start))
# Plot results
plt.subplot(1, 3, 1)
def eval_psnr_and_ssim(im1, im2):
im1_t = img_as_float(im1)
im2_t = img_as_float(im2)
im1_t = rgb2ycbcr(im1_t)[:, :, 0:1] / 255.0
im2_t = rgb2ycbcr(im2_t)[:, :, 0:1] / 255.0
if args.scale > 1:
im1_t = mod_crop(im1_t, args.scale)
im2_t = mod_crop(im2_t, args.scale)
im1_t = crop_boundaries(im1_t, int(args.scale)+6)
im2_t = crop_boundaries(im2_t, int(args.scale)+6)
psnr_val = compare_psnr(im1_t, im2_t)
ssim_val = compare_ssim(
im1_t,
im2_t,
win_size=11,
def __get_images_cropped_and_scaled(self, image_file_name: str):
_input = self.get_model().get_inputs()[self._input_output_id]
input_shape = list(filter(lambda item: item is not None, _input['shape']))
target_channels = min(input_shape[1:])
target_size = input_shape[-2:]
if not os.path.isfile(image_file_name) or not os.access(image_file_name, os.R_OK):
self.get_model().set_error(MindError(
ERROR_CODE_FILTER_FILE_IS_UNREACHABLE,
'{}: file [{}] is not accessible',
[self.__class__.__name__, image_file_name]
))
return
img = skimage.img_as_float(skimage.io.imread(image_file_name)).astype(np.float32)
img = self.get_rescaled(img, target_size[0], target_size[1])
img = self.crop_center(img, target_size[0], target_size[1])
# switch to CHW
img = img.swapaxes(1, 2).swapaxes(0, 1)
# remove mean for better results
img = img * 255 - 128
# add batch size
img = img[np.newaxis, :, :, :].astype(np.float32)
return img
corner_to_id = dict([((x['img_x'], x['img_y']), y) for y, x in sample_data['point_dict'].items()])
for room_i in range(len(all_room_corners)):
room_corners_id = [corner_to_id[x] for x in all_room_corners[room_i]]
all_room_corners[room_i] = room_corners_id
image, mean_normal, room_masks_map, point_dict = augment_rotation(image, mean_normal, room_masks_map,
sample_data['point_dict'])
sample_data['point_dict'] = point_dict
for room_i in range(len(all_room_corners)):
room_corners_id = all_room_corners[room_i]
rot_room_corners = [(point_dict[x]['img_x'], point_dict[x]['img_y']) for x in room_corners_id]
all_room_corners[room_i] = rot_room_corners
normalized_image = skimage.img_as_float(image[0]) # only keep one channel since they are highly overlapped
corner_annot, corner_gt_map = generate_corner_annot(sample_data['point_dict'], sample_data['lines'])
edge_gt_map = generate_edge_annot(all_room_corners, self.im_size)
# for testing the augmentation
# from scipy.misc import imsave
# import cv2
# test_img = image.transpose([1, 2, 0]).astype(np.float32) + (np.stack([corner_gt_map[0]] * 3, -1) * 255).astype(np.float32)
# test_img = np.clip(test_img, 0, 255).astype(np.uint8)
# for corner_id, corner_data in corner_annot.items():
# if 0 < corner_data['x'] < 256 and 0 < corner_data['y'] < 256:
# for connection in corner_data['connections']:
# vec_x = np.cos(connection * 10 / 180 * np.pi)
# vec_y = np.sin(connection * 10 / 180 * np.pi)
# end_x = int(np.round(corner_data['x'] + 10 * vec_x))
# end_y = int(np.round(corner_data['y'] - 10 * vec_y))
# if 0 < end_x < 256 and 0 < end_y < 256: