I have some images(say 5) and each having different shapes. I want to concatenate into one single image for my project report. Can you please provide an easy way using opencv and python?
The resulting image is similar to below.
In numpy I tried something like this, it works but only for two images.
r = np.concatenate((images[1][:, :, 1], images[1][:, :, 3]), axis=1)
Getting the results that you show in the screenshot might require some more tinkering, but simply stacking the images on top of eachother can be acomplished like this:
import cv2
import numpy as np
image_names = ['original_field_1_0.PNG','original_field_1_1.PNG','original_field_1_3.PNG','original_field_1_4.PNG','original_field_1_5.PNG']
images = []
max_width = 0 # find the max width of all the images
total_height = 0 # the total height of the images (vertical stacking)
for name in image_names:
# open all images and find their sizes
images.append(cv2.imread(name))
if images[-1].shape[1] > max_width:
max_width = images[-1].shape[1]
total_height += images[-1].shape[0]
# create a new array with a size large enough to contain all the images
final_image = np.zeros((total_height,max_width,3),dtype=np.uint8)
current_y = 0 # keep track of where your current image was last placed in the y coordinate
for image in images:
# add an image to the final array and increment the y coordinate
final_image[current_y:image.shape[0]+current_y,:image.shape[1],:] = image
current_y += image.shape[0]
cv2.imwrite('fin.PNG',final_image)
The basic idea is to find the total size of the images first, then create an array of that size and finally set the pixels in those ranges to that of each individual image while iterating downwards (or sideways, depending on what you want).
You can also implement threshold values for when you want to start another row or column.
This modification of #ajayramesh's solution worked for me. This function takes in a list of images and outputs a single image where all input images are stacked vertically:
def get_one_image(img_list):
max_width = 0
total_height = 200 # padding
for img in img_list:
if img.shape[1] > max_width:
max_width = img.shape[1]
total_height += img.shape[0]
# create a new array with a size large enough to contain all the images
final_image = np.zeros((total_height, max_width, 3), dtype=np.uint8)
current_y = 0 # keep track of where your current image was last placed in the y coordinate
for image in img_list:
# add an image to the final array and increment the y coordinate
image = np.hstack((image, np.zeros((image.shape[0], max_width - image.shape[1], 3))))
final_image[current_y:current_y + image.shape[0], :, :] = image
current_y += image.shape[0]
return final_image
I modified code to make it a simple function, may be useful for others.
def get_one_image(images):
img_list = []
padding = 200
for img in images:
img_list.append(cv2.imread(img))
max_width = []
max_height = 0
for img in img_list:
max_width.append(img.shape[0])
max_height += img.shape[1]
w = np.max(max_width)
h = max_height + padding
# create a new array with a size large enough to contain all the images
final_image = np.zeros((h, w, 3), dtype=np.uint8)
current_y = 0 # keep track of where your current image was last placed in the y coordinate
for image in img_list:
# add an image to the final array and increment the y coordinate
final_image[current_y:image.shape[0] + current_y, :image.shape[1], :] = image
current_y += image.shape[0]
cv2.imwrite('out.png', final_image)
Related
I'm currently trying to create an image preprocessor that adds specific noise for AI training. In this case, I'm trying to add contour lines over the top of my input image that resemble sketch lines.
So far I have been able to get these lines drawn on my image, but they are very sharp and pixelated, which obviously doesn't resemble real artist-drawn lines. I need some way to apply a slight blur to soften these edges, but so far I have not been able to do this.
Here is a visual guide to what I am trying to achieve:
I need to find the contours in image (A) and draw them onto a new layer with alpha channel (B). I then need to blur these lines (C) and paste it back onto the original image (D).
Here is the section I'm having problems with:
# Convert the image to a NumPy array
augmented_image = np.array(augmented_image)
augmented_shape = augmented_image.shape
# Convert image back to color
grey_image = color.rgb2gray(augmented_image)
# Detect the contours of the image using the Canny edge detector
edges = feature.canny(grey_image, sigma=3)
# Create a blank image with dimensions 256 x 256
blank_image = np.zeros((256, 256, 4))
# Create a copy of the image to draw the contours on and convert to 4 layers rgba
alpha = np.ones((augmented_image.shape[0], augmented_image.shape[1], 1), dtype=augmented_image.dtype) * 255
augmented_image = np.concatenate([augmented_image, alpha], axis=2)
# Iterate over the contours
for contour in measure.find_contours(edges, 0.8):
# Set offset
offset = 10
# Select a random point along the contour
point = np.random.randint(0, len(contour))
start_row, start_col = contour[point]
start_row = start_row + offset
start_col = start_col + offset
start_row = np.clip(start_row, 0, augmented_shape[0] - 1)
start_col = np.clip(start_col, 0, augmented_shape[0] - 1)
# Select a random point along the contour that is not the same as the first point
point = np.random.randint(0, len(contour))
while point == start_row:
point = np.random.randint(0, len(contour))
end_row, end_col = contour[point]
end_row = end_row + offset
end_col = end_col + offset
end_row = np.clip(end_row, 0, augmented_shape[0] - 1)
end_col = np.clip(end_col, 0, augmented_shape[0] - 1)
# Draw the line on the image using the draw.line function
rr, cc = draw.line(int(start_row), int(start_col), int(end_row), int(end_col))
blank_image[rr, cc] = 30
# Smooth the contour lines using the gaussian function
blank_image = filters.gaussian(blank_image, sigma=1)
# Make sure image is same data-type
blank_image = blank_image.astype(augmented_image.dtype)
# Create a mask for the contour lines
blank_alpha = blank_image[:, :, 3:]
mask = np.any(blank_alpha > 0, axis=2)
# Apply the smooth image to the masked region of the original image
augmented_image[mask] = blank_image[mask]
# Convert image back to 3 layers rgb
augmented_image = augmented_image[:, :, :3]
I know that the problem lies somewhere in the 'mask' variable definition. Something about it being a boolean type just pastes a line of pure black squares on my image rather than the expected blurred line. No amount of messing with layer order or adding extra layers to copy from has fixed this.
Doing this process without trying to blur the lines works great, minus the fact that it's very pixelated and doesn't fit the style of the training data. Blurring the image without trying to re-combine anything produces an adequate blurred line as well, however the entire image is blurred.
Here's what I can produce without the blurring process, and a rough idea of what I would like the final product to look like (made in Photoshop)
It's only when I try to mask and combine that this becomes a problem. I will post the full code below for anyone to run on their own system:
import random
import numpy as np
import skimage
from skimage.transform import rotate, resize
from skimage import draw, feature, color, measure, filters, util
from skimage.util import random_noise
import PIL
from PIL import Image
import os
import argparse
import cv2
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from pathlib import Path
import imghdr
# Set parser args
parser = argparse.ArgumentParser()
parser.add_argument("--dirty_dir", help="path to folder containing dirty images")
parser.add_argument("--clean_dir", help="path to folder containing clean images")
parser.add_argument("--dirty_savedir", help="path to dirty output folder")
parser.add_argument("--clean_savedir", help="path to clean output folder")
a = parser.parse_args()
# Set folder paths
dirty_dir = a.dirty_dir + '/'
clean_dir = a.clean_dir + '/'
dirty_savedir = a.dirty_savedir + '/'
clean_savedir = a.clean_savedir + '/'
print(f"Source Folder: {dirty_dir}")
print(f"Source Folder: {clean_dir}")
print(f"Output Folder: {dirty_savedir}")
print(f"Output Folder: {clean_savedir}")
def augment_image(image, filename, clean_dir):
for i in range(8):
# Create list for clean imgs
clean_list = []
# Randomly select a 256x256 region
w, h = image.size[0], image.size[1]
print(w,h)
top = random.randint(0, h - 256)
left = random.randint(0, w - 256)
right = left + 256
bottom = top + 256
dims = [left, top, right, bottom]
print(f'{filename} dimensions:{dims}')
# Add dimensions to clean_list
clean_list.extend(dims)
augmented_image = image.crop((dims))
print(f'{filename} shape: {augmented_image.size}')
# Randomly rotate the image by 90, 180, or 270 degrees
angle = random.choice([0, 90, 180, 270])
augmented_image = augmented_image.rotate(angle)
# Add angle to list
clean_list.append(angle)
# Randomly flip the image horizontally
flip_lr = random.choice([True, False])
if flip_lr == True:
augmented_image = augmented_image.transpose(Image.FLIP_LEFT_RIGHT)
clean_list.append("flip_lr")
else:
clean_list.append("none")
# Randomly flip the image vertically
flip_tb = random.choice([True, False])
if flip_tb == True:
augmented_image = augmented_image.transpose(Image.FLIP_TOP_BOTTOM)
clean_list.append("flip_tb")
else:
clean_list.append("none")
# Convert the image to a NumPy array
augmented_image = np.array(augmented_image)
augmented_shape = augmented_image.shape
# Convert image back to color
grey_image = color.rgb2gray(augmented_image)
# Detect the contours of the image using the Canny edge detector
edges = feature.canny(grey_image, sigma=3)
# Create a blank image with dimensions 256 x 256
blank_image = np.zeros((256, 256, 4))
# Create a copy of the image to draw the contours on and convert to 4 layers rgba
alpha = np.ones((augmented_image.shape[0], augmented_image.shape[1], 1), dtype=augmented_image.dtype) * 255
augmented_image = np.concatenate([augmented_image, alpha], axis=2)
# Iterate over the contours
for contour in measure.find_contours(edges, 0.8):
# Set offset
offset = 10
# Select a random point along the contour
point = np.random.randint(0, len(contour))
start_row, start_col = contour[point]
start_row = start_row + offset
start_col = start_col + offset
start_row = np.clip(start_row, 0, augmented_shape[0] - 1)
start_col = np.clip(start_col, 0, augmented_shape[0] - 1)
# Select a random point along the contour that is not the same as the first point
point = np.random.randint(0, len(contour))
while point == start_row:
point = np.random.randint(0, len(contour))
end_row, end_col = contour[point]
end_row = end_row + offset
end_col = end_col + offset
end_row = np.clip(end_row, 0, augmented_shape[0] - 1)
end_col = np.clip(end_col, 0, augmented_shape[0] - 1)
# Draw the line on the image using the draw.line function
rr, cc = draw.line(int(start_row), int(start_col), int(end_row), int(end_col))
blank_image[rr, cc] = 30
# Smooth the contour lines using the gaussian function
blank_image = filters.gaussian(blank_image, sigma=1)
# Make sure image is same data-type
blank_image = blank_image.astype(augmented_image.dtype)
# Create a mask for the contour lines
blank_alpha = blank_image[:, :, 3:]
mask = np.any(blank_alpha > 0, axis=2)
# Apply the smooth image to the masked region of the original image
augmented_image[mask] = blank_image[mask]
# Convert image back to 3 layers rgb
augmented_image = augmented_image[:, :, :3]
## Add more noise types (lines, wrinkles, color)/make noise random chance to occur ##
# Add random noise to the image
noise = random_noise(augmented_image, mode='pepper', amount=0.011)
# Convert the noisy image back to a PIL image
augmented_image = np.random.random_sample(augmented_image.shape) * 255
augmented_image = np.array(255 * noise, dtype=np.uint8)
augmented_image = Image.fromarray(augmented_image)
# Save file
augmented_image.save(dirty_savedir + '_' + str(i) + '_' + filename)
print(clean_list)
# Function to mirror edits onto clean images
def clean_aug(clean_dir, clean_list):
# Open clean directory
for filename in os.listdir(f"{clean_dir}"):
# Rule out any weird Mac files
if not filename.startswith("._"):
with Image.open(clean_dir + filename) as image:
# Define clean dimensions
clean_dims = clean_list[0:4]
# Crop image
clean_augmented = image.crop((clean_dims))
# Rotate clean image
clean_augmented = clean_augmented.rotate(clean_list[4])
# Flip clean image
if clean_list[5] == 'flip_lr':
clean_augmented = clean_augmented.transpose(Image.FLIP_LEFT_RIGHT)
if clean_list[6] == 'flip_tb':
clean_augmented = clean_augmented.transpose(Image.FLIP_TOP_BOTTOM)
# Save clean images
clean_augmented.save(clean_savedir + '_' + str(i) + '_' + filename)
print("Clean alterations copied successfully")
clean_aug(clean_dir, clean_list)
# Clean up unnecessary files
def file_scrub():
dirty_dir = dirty_savedir
image_extensions = [".png", ".jpg"] # add there all your images file extensions
img_type_accepted_by_tf = ["bmp", "gif", "jpeg", "png"]
for filepath in Path(dirty_dir).rglob("*"):
if filepath.suffix.lower() in image_extensions:
img_type = imghdr.what(filepath)
if img_type is None:
print(f"{filepath} is not an image")
elif img_type not in img_type_accepted_by_tf:
print(f"{filepath} is a {img_type}, not accepted by TensorFlow")
def image_aug(dirty_dir, clean_dir):
for filename in os.listdir(f"{dirty_dir}"):
# Check if the filename starts with "._"
if not filename.startswith("._"):
with Image.open(dirty_dir + filename) as image:
# Open the image
augment_image(image, filename, clean_dir)
image_aug(dirty_dir, clean_dir)
file_scrub()
Apologies for the cumbersome codebase. I just wanted to minimize the risk of discrepancies arising from an attempt at concatenating my script. If there is any clarification I can provide please let me know!
I have a directory of image patches that are all the same size (33x33), the images are ordered so that the first 7 images are row 1, then the next 7 images are row 2, etc. I'm currently trying to reconstruct the original image using the 33x33 patches, but I am having trouble with the rows/cols organization. Any help with this is much appreciated! Here is my code for splitting the image into tiles:
def split_images():
img_arr = []
for image_path in image_paths:
image = cv2.imread(image_path, cv2.IMREAD_COLOR) # read in image
for i in range(0, image.shape[0], 33): # loop through height-wise pixels of image, striding by 33
for j in range(0, image.shape[1], 33): # loop through width-wise pixels of image, striding by 33
images = image[i:i + 33, j:j + 33, :] # creating label image from h,w pixel to 33 pixels to the right and down
img_arr.append(images) # create list from label images
# write images
cv2.imwrite(f"../outputs/subimages/subimage{i}_{j}.png", images)
return {"images": img_arr}
This splits the image into the aforementioned 33x33 tiles, but stitching them back together is where I'm having trouble. I can currently stitch the image back together in one long row, but I'm unsure of how to stitch the images back into their original order. This is my current stitching code:
def merge_images():
space_between_row = 10
new_image_path = 'result.jpg'
im_dirs = glob.glob('../outputs/subimages')
# get sorted list of images
im_path_list = [[path.join(p, f) for f in sorted(listdir(p))] for p in im_dirs]
# open images and calculate total widths and heights
im_list = []
total_width = 0
total_height = 0
for path_list in im_path_list:
images = list(map(Image.open, path_list))
widths, heights = zip(*(i.size for i in images))
total_width = max(total_width, sum(widths))
total_height += max(heights)
im_list.append(images)
# concat images
new_im = Image.new('RGB', (total_width, total_height))
y_offset = 0
for images in im_list:
x_offset = 0
max_height = 0
for im in images:
new_im.paste(im, (x_offset, y_offset))
x_offset += im.size[0]
max_height = max(im.size[1], max_height)
y_offset = y_offset + max_height + space_between_row
# show and save
new_im.show()
new_im.save(new_image_path)
So for this code to work properly, i need it to center the new image in the black space with borders around it. I've been trying to take the first image dimensions and subtract the new enlarged empty dimensions but I can't seem to get it to work. I'm not sure what to do at this point. I've managed to duplicate the picture i just need to center it now.
import numpy as np
# read in image (in the same folder)
image = cv2.imread("cones11.png")
# get size of image
numRows = image.shape[0] # height of image
numCols = image.shape[1] # width of image
print(image.shape[0])
print(image.shape[1])
#scalar
scalar = 1.2
#newdimensions nxn
n = int (scalar * numRows)
n1 = int(scalar * numCols)
shift = n/2
shift1 = n1/2
# create an empty color image
emptyIm = np.zeros((n, n1, 3)) # (size, data type)
# iterate over all the pixels of your image
for i in range(numRows): # iterate over height of image, y-coordinates
for j in range(numCols): # iteratve over the width of image, x-coordinates
# access values at a pixel:
# image[i][j][0]: blue value stored at pixel (i,j)
# image[i][j][1]: green value stored at pixel (i,j)
# image[i][j][2]: red value stored at pixel (i,j)
#image[i][j][0] = emptyIm[i][j][0]
#image[i][j][1] = emptyIm[i][j][1]
#image[i][j][2] = emptyIm[i][j][2]
emptyIm[i,j] = emptyIm[j,i] - image[int(shift)-1, int(shift1)-1]
emptyIm[i][j][0] = image[i][j][0]
emptyIm[i][j][1] = image[i][j][1]
emptyIm[i][j][2] = image[i][j][2]
#emptyIm[i][j] = emptyIm[i+n][i+n]
#enlarging image
# n = 2*emptyIm[i][j]
cv2.imshow("xd", image)
cv2.imshow("enlarged", emptyIm/255.0)
cv2.waitKey(0)```
My machine learning algorithm has already learned the 70000 images in the MNIST database. I want to test it on an image not included in the MNIST dataset. However, my predict function cannot read the array representation of my test image.
How do I test my algorithm on an external image?
Why is my code failing?
PS I'm using python3
Error Received:
Traceback (most recent call last):
File "hello_world2.py", line 28, in <module>
print(sgd_clf.predict(arr))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/linear_model/base.py", line 336, in predict
scores = self.decision_function(X)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/linear_model/base.py", line 317, in decision_function
% (X.shape[1], n_features))
ValueError: X has 15 features per sample; expecting 784
Code:
# Common Imports
import numpy as np
from sklearn.datasets import fetch_mldata
from sklearn.linear_model import SGDClassifier
from PIL import Image
from resizeimage import resizeimage
# loading and learning MNIST data
mnist = fetch_mldata('MNIST original')
x, y = mnist["data"], mnist["target"]
sgd_clf = SGDClassifier(random_state=42)
sgd_clf.fit(x, y)
# loading and converting to array a non-MNIST image of a "5", which is in the same folder
img = Image.open("5.png")
arr = np.array(img)
# trying to predict that the image is a "5"
img = Image.open("5.png")
img = img.convert('L') #makes it greyscale
img = resizeimage.resize_thumbnail(img, [28,28])
arr = np.array(img)
print(sgd_clf.predict(arr)) # ERROR... why????????? How do you fix it?????
It's not simply a matter of resizing, the image needs the digit centered and white on black etc. I've been working on a function to this job. This is the current version that uses opencv, although it could do with further improvement, including using PIL instead of opencv, but it should give an idea of the steps required.
def open_as_mnist(image_path):
"""
Assume this is a color or grey scale image of a digit which has not so far been preprocessed
Black and White
Resize to 20 x 20 (digit in center ideally)
Sharpen
Add white border to make it 28 x 28
Convert to white on black
"""
# open as greyscale
image = cv2.imread(image_path, 0)
# crop to contour with largest area
cropped = do_cropping(image)
# resizing the image to 20 x 20
resized20 = cv2.resize(cropped, (20, 20), interpolation=cv2.INTER_CUBIC)
cv2.imwrite('1_resized.jpg', resized20)
# gaussian filtering
blurred = cv2.GaussianBlur(resized20, (3, 3), 0)
# white digit on black background
ret, thresh = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY_INV)
padded = to20by20(thresh)
resized28 = padded_image(padded, 28)
# normalize the image values to fit in the range [0,1]
norm_image = np.asarray(resized28, dtype=np.float32) / 255.
# cv2.imshow('image', norm_image)
# cv2.waitKey(0)
# # Flatten the image to a 1-D vector and return
flat = norm_image.reshape(1, 28 * 28)
# return flat
# normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [(255 - x) * 1.0 / 255.0 for x in flat]
return tva
def padded_image(image, tosize):
"""
This method adds padding to the image and makes it to a tosize x tosize array,
without losing the aspect ratio.
Assumes desired image is square
:param image: the input image as numpy array
:param tosize: the final dimensions
"""
# image dimensions
image_height, image_width = image.shape
# if not already square then pad to square
if image_height != image_width:
# Add padding
# The aim is to make an image of different width and height to a sqaure image
# For that first the biggest attribute among width and height are determined.
max_index = np.argmax([image_height, image_width])
# if height is the biggest one, then add padding to width until width becomes
# equal to height
if max_index == 0:
#order of padding is: top, bottom, left, right
left = int((image_height - image_width) / 2)
right = image_height - image_width - left
padded_img = cv2.copyMakeBorder(image, 0, 0,
left,
right,
cv2.BORDER_CONSTANT)
# else if width is the biggest one, then add padding to height until height becomes
# equal to width
else:
top = int((image_width - image_height) / 2)
bottom = image_width - image_height - top
padded_img = cv2.copyMakeBorder(image, top, bottom, 0, 0, cv2.BORDER_CONSTANT)
else:
padded_img = image
# now that it's a square, add any additional padding required
image_height, image_width = padded_img.shape
padding = tosize - image_height
# need to handle where padding is not divisiable by 2
left = top = int(padding/2)
right = bottom = padding - left
resized = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT)
return resized
If you want to read a picture then resize it, please try
In [1]: import PIL.Image as Image
In [2]: img = Image.open('2.jpg', mode='r')
In [3]: img.mode
Out[3]: 'RGB'
In [4]: img.size
Out[4]: (2880, 1800)
In [5]: img_new = img.resize([4000, 4000], Image.ANTIALIAS)
In [6]: img_new2 = img.resize([32, 32], Image.ANTIALIAS)
Docs are here
This is the 2.jpg, sorry, it is not a digit.
This picture is from the Internet, sorry, I forget the source.
If you encounter the mode is 'RGBA', I recommend you transfer it to 'RGB' mode,
newimg = Image.new('RGB', img.size)
newimg.paste(img, mask=img.split()[3])
return newimg
Please try this:
img = Image.open("5.png")
img = img.resize((28,28))
img = img.convert('L') #makes it greyscale
I have an image consisting of 100 pixels. for each pixel, I want to pad it with zeros (if on the edge) so that it's in the center, concatenate with neighboring pixels and generate a new 10x10 image. Thus I want to generate 100 images from the original image by sliding through each pixel along the row. e.g. for pixel[0,0], I want to add 4 zero columns on right, 4 zero rows on top, neighboring 5 column pixels on right and neighboring 5 row pixels on the bottom.
Can someone guide me on how this is done for a RGB image with numpy?
def unpickle_im(file, type):
import Image
im1 = Image.open(file)
im1p = np.asarray(im1, dtype=type)
return im1p
imc2p = unpickle_im('tmp/RGB-00000.png', 'float32')
##imc2p.shape = (10,10,3)
padded = np.zeros(10,10,3) ##Create a padded image filled with zeros
for i in xrange(im2cp.shape[0]):
for j in xrange(im2cp.shape[1]):
if(i < 5 or j < 5) :
new_im2cp = np.pad(im2cp[i:5, j:5], ((4-i,4-j),(0,0)))
else:
new_im2cp = np.pad(im2cp[i-4:i+5, j-4:j+5])
edit: adding the correct snippet after #dabhaid's post:
from PIL import Image
import numpy as np, time
im_array = np.random.rand(10,10,3)
pad = 4
padded_array = np.pad(im_array, ((pad,pad+1),(pad,pad+1),(0,0)), 'constant')
for i in xrange(im_array.shape[0]):
for j in xrange(im_array.shape[1] ):
temp_im = padded_array[i:i+10, j:j+10]
# print temp_im.shape
if i == 0 and j == 0:
new_im = temp_im[np.newaxis,...]
else:
new_im = np.vstack([new_im, temp_im[np.newaxis,...]])
I'm going to assume you have an RGB image (rather than an RGBA). As per the comments, is this what you want?
from PIL import Image
import numpy as np
image = Image.open('100.png')
im_array = np.array(image)
stack = np.array(100, 20, 20, 3) #100 of the padded arrays
for i in xrange(im_array.shape[0]):
for j in xrange(im_array.shape[1]):
padded = np.zeros((20,20,3))
padded[9][9] = im_array[i][j]
stack[i*j] = padded
It seems wasteful, memory-wise.
edit in response to question update
instead of padding the new images conditionally, pad the original image and then just copy sub-images out of it:
from PIL import Image
import numpy as np
image = Image.open('100.png')
im_array = np.array(image)
pad = 4 #pixels
padded_array = np.pad(im_array, ((pad,pad+1),(pad,pad+1),(0,0)), 'constant')
# pad 4 elements to the left, right, up and down, but leave the pixel values alone
# default value is zero
for i in xrange(im_array.shape[0] - (pad + pad+1)):
for j in xrange(im_array.shape[0] - (pad + pad+1)):
new_imarray = padded_array[i:i+9, j:j+9]
# do what you need with the new image
from PIL import Image
import numpy as np, time
im_array = np.random.rand(10,10,3)
pad = 4
padded_array = np.pad(im_array, ((pad,pad+1),(pad,pad+1),(0,0)), 'constant')
for i in xrange(im_array.shape[0]):
for j in xrange(im_array.shape[1] ):
temp_im = padded_array[i:i+10, j:j+10]
# print temp_im.shape
if i == 0 and j == 0:
new_im = temp_im[np.newaxis,...]
else:
new_im = np.vstack([new_im, temp_im[np.newaxis,...]])