def seam_carve(img):
"""
Seam carve image
:param img: PIL image object
:return: PIL image object
"""
# Convert to skimage image
img_to_convert = img.copy()
img_to_convert = pil_to_skimage(img_to_convert)
# Energy Map, used to determine which pixels will be removed
eimg = filters.sobel(color.rgb2gray(img_to_convert))
# (height, width)
img_dimensions = img_to_convert.shape
# Squish width if width >= height, squish height if height > width
# Number of pixels to keep along the outer edges (5% of largest dimension)
# Number of seams to be removed, (1 to 10% of largest dimension)
if img_dimensions[1] >= img_dimensions[0]:
mode = "horizontal"
border = round(img_dimensions[1] * 0.05)
num_seams = random.randint(1, round(0.1*img_dimensions[1]))
else:
mode = "vertical"
border = round(img_dimensions[0] * 0.05)
num_seams = random.randint(1, round(0.1*img_dimensions[0]))
try:
img_to_convert = transform.seam_carve(img_to_convert, eimg, mode, num_seams, border)
except Exception as e:
print("Unable to seam_carve: " + str(e))
# Convert back to PIL image
img_to_convert = skimage_to_pil(img_to_convert)
return img_to_convert
python类rgb2gray()的实例源码
def __init__(self, root, split):
if split not in ['train', 'test', 'all']:
raise ValueError
dir = os.path.join(root, split)
filenames = glob.glob(os.path.join(dir, '*.png'))
if split == 'all':
filenames = glob.glob(os.path.join(root, 'train/*.png'))
filenames.extend(glob.glob(os.path.join(root, 'test/*.png')))
filenames = sorted(
filenames, key=lambda x: int(os.path.basename(x).split('.')[0]))
images = []
for f in filenames:
img = plt.imread(f)
img[img != 1] = 0
images.append(resize(rgb2gray(img), [48, 48], mode='constant'))
self.images = np.array(images, dtype=np.float32)
self.images = self.images.reshape([len(images), 48, 48, 1])
action_filename = os.path.join(root, 'actions.txt')
with open(action_filename) as infile:
actions = np.array([float(l) for l in infile.readlines()])
self.actions = actions[:len(self.images)].astype(np.float32)
self.actions = self.actions.reshape(len(actions), 1)
def all_states(cls):
_env = gym.make('Pendulum-v0').env
width = GymPendulumDataset.width
height = GymPendulumDataset.height
X = np.zeros((360, width, height))
for i in range(360):
th = i / 360. * 2 * np.pi
state = _env.render_state(th)
X[i, :, :] = resize(rgb2gray(state), (width, height), mode='reflect')
_env.close()
_env.viewer.close()
return X
def load_image(filepath, as_grey=False, dtype='uint8', no_alpha=True):
"""
Load image as numpy array from given filepath.
Supported formats: gif, png, jpg, bmp, tif, npy
>>> img = load_image('tests/data/img_formats/nut_color.jpg')
>>> shapestr(img)
'213x320x3'
:param string filepath: Filepath to image file or numpy array.
:param bool as_grey:
:return: numpy array with shapes
(h, w) for grayscale or monochrome,
(h, w, 3) for RGB (3 color channels in last axis)
(h, w, 4) for RGBA (for no_alpha = False)
(h, w, 3) for RGBA (for no_alpha = True)
pixel values are in range [0,255] for dtype = uint8
:rtype: numpy ndarray
"""
if filepath.endswith('.npy'): # image as numpy array
arr = np.load(filepath).astype(dtype)
arr = rgb2gray(arr) if as_grey else arr
else:
# img_num=0 due to
# https://github.com/scikit-image/scikit-image/issues/2406
arr = ski.imread(filepath, as_grey=as_grey, img_num=0).astype(dtype)
if arr.ndim == 3 and arr.shape[2] == 4 and no_alpha:
arr = arr[..., :3] # cut off alpha channel
return arr
def rgb2gray(image):
"""
RGB scale image to grayscale image
>>> image = np.eye(3, dtype='uint8') * 255
>>> rgb2gray(image)
array([[255, 0, 0],
[ 0, 255, 0],
[ 0, 0, 255]], dtype=uint8)
:param numpy array image: Numpy array with range [0,255] and dtype 'uint8'.
:return: grayscale image
:rtype: numpy array with range [0,255] and dtype 'uint8'
"""
return floatimg2uint8(skc.rgb2gray(image))
def process_image(img):
return 2 * color.rgb2gray(transform.rescale(img[34:194], 0.5)) - 1
def process_image(obs):
return 2 * color.rgb2gray(obs) - 1.0
def get_initial_state(self, observation, last_observation):
processed_observation = np.maximum(observation, last_observation)
processed_observation = np.uint8(resize(rgb2gray(processed_observation), (FRAME_WIDTH, FRAME_HEIGHT)) * 255)
state = [processed_observation for _ in xrange(STATE_LENGTH)]
return np.stack(state, axis=0)
def preprocess(observation, last_observation):
processed_observation = np.maximum(observation, last_observation)
processed_observation = np.uint8(resize(rgb2gray(processed_observation), (FRAME_WIDTH, FRAME_HEIGHT)) * 255)
return np.reshape(processed_observation, (1, FRAME_WIDTH, FRAME_HEIGHT))
def preprocessImage(self, img):
'''Compute luminance (grayscale in range [0, 1]) and resize to (D, D).'''
img = rgb2gray(img) # compute luminance 210x160
img = resize(img, (self.agent.D, self.agent.D), mode='constant') # resize image
return img
def preprocessImage(self, img):
'''Compute luminance (grayscale in range [0, 1]) and resize to (D, D).'''
img = rgb2gray(img) # compute luminance 210x160
img = resize(img, (self.D, self.D), mode='constant') # resize image
return img
def _preprocessImage(self, img):
'''Compute luminance (grayscale in range [0, 1]) and resize to (D, D).'''
img = rgb2gray(img) # compute luminance 210x160
img = resize(img, (self.agent.D, self.agent.D), mode='constant') # resize image
return img
def plot_figure_video_rigidity_example(image, rigidity):
# Figure 93
PTH='./figure_rigidity_example/'
if not os.path.isdir(PTH):
os.makedirs(PTH)
I_bw = color.rgb2gray(image)
I_bw = np.dstack((I_bw,I_bw,I_bw))*0.5
I_bw[:,:,0][rigidity==1] += 0.5
I_bw[:,:,2][rigidity==0] += 0.5
io.imsave(PTH+'image.png', image)
io.imsave(PTH+'rigidity.png', I_bw)
def get_preprocessed_frame(self, observation):
if isinstance(self.env.observation_space, Discrete):
expanded_obs = np.zeros(self.env.observation_space.n, dtype=np.float32)
expanded_obs[observation] = 1
return expanded_obs
elif len(observation.shape) > 1:
if not self.use_rgb:
observation = rgb2gray(observation)
return resize(observation, (self.resized_width, self.resized_height))
else:
return observation
def get_puzzle_pieces(self):
"""
returns the puzzle pieces, as well as their true locations in row major numbering format, as a dictionary,
where the key, is row_major puzzle_piece_id and the value is the piece image itself
:return: The dictionary of piece_id => piece_image
"""
result = dict()
for piece_id, piece in enumerate(self.tiles):
piece_image = np.array(piece.image)
result[piece_id] = rgb2gray(piece_image)
return result
def hog_gen_windows(work_tuple):
image_arr, coords = work_tuple
lx1,ly1,rx1,ry1 = coords
if image_arr.ndim > 2:
image_arr = resize(color.rgb2gray(image_arr)[ly1:ry1, lx1:rx1], (120, 120))
hog_image_rescaled = generate_hog_features(image_arr)
return hog_image_rescaled
def hog_gen(image, path=0):
if path != 0 and image == 0:
image = imread(path)
if image.ndim > 2:
image = color.rgb2gray(image)
hog_image_rescaled = generate_hog_features(image)
return hog_image_rescaled
def generate_test_set(color_img):
img_arr = color.rgb2gray(color_img)
img_transformed = resize(img_arr, output_shape=(120, 120))
hog_image = generate_hog_features(img_transformed)
return hog_image
def generate_hog_features(filename):
input_image = io.imread(filename)
gray_image = color.rgb2gray(input_image)
# 87% for orientations=8, pixels_per_cell=(4, 4), cells_per_block=(1, 1)
fd, hog_image = hog(gray_image, orientations=8, pixels_per_cell=(4, 4),
cells_per_block=(1, 1), visualise=True)
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))
return hog_image_rescaled
def save_hog_image_comparison(filename):
input_image = io.imread(filename)
gray_image = color.rgb2gray(input_image)
out_filename = "hog/" + filename
# 87% for orientations=8, pixels_per_cell=(4, 4), cells_per_block=(1, 1)
fd, hog_image = hog(gray_image, orientations=8, pixels_per_cell=(4, 4),
cells_per_block=(1, 1), visualise=True)
# io.imsave("hog/" + filename, hog_image)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)
ax1.axis('off')
ax1.imshow(gray_image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')
# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))
ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.savefig(out_filename)
plt.close()
return hog_image