Here is the code:
# To crop image
def crop(image,origin,height,width):
ret=[]
row = 0
col = 0
for i in image:
rgb =[] # to store row of pixels
for j in i:
# Store the pixels of crop boundary area only
if row < (origin[0] + height) and col <
(origin[1]+width):
rgb.append(j)
col += 1
if rgb:
ret.append(rgb)
row += 1
col = 0
return ret
# To extract gray color
def color2gray(image):
gray=[]
for i in image:
rgb =[] # to store row of pixels
for j in i:
rgb.append(sum(j)//3)
gray.append(rgb)
return gray
# To extract one color layer
def extract_layer(image,color):
layer = []
if color == 'red':
idx = 0
elif color == 'green':
idx = 1
elif color == 'blue':
idx = 2
for i in image:
rgb = []
for j in i:
rgb.append(j[idx]) # extract only color index value
layer.append(rgb)
return layer
# Test program
image=[[[1,1,1],[2,2,2],[3,3,3]],
[[4,4,4],[5,5,5],[6,6,6]],
[[7,7,7],[8,8,8],[9,9,9]] ]
print("crop(image,(0,0),1,2)) of image ",image
,"is",crop(image,(0,0),1,2))
image= [ [[1,1,2],[2,5,2]],
[[3,4,4],[5,9,5]] ]
print("color2gray(image) of image",image,"is",
color2gray(image))
print("extract_layer(image, 'red') of image",
image,"is",extract_layer(image, 'red'))
Sample output
# To crop image def crop (image, origin, height, width): ret=[] row = 0 col = 0 for i in image: rgb = [] # to store row of pixels for j in i: # Store the pixels of crop boundary area only if row < (origin[0] + height) and col < (origin[1]+width): rgb.append(j) col += 1 if rgb: ret.append(rgb) row += 1 col = 0 return ret 19 20 # To extract gray color def color2gray(image): gray=[] for i in image: rgb = [] # to store row of pixels for j in i: rgb.append(sum(j)//3) gray.append(rgb) return gray 30 - 31 # To extract one color layer def extract_layer(image, color): layer = [] if color == 'red': idx = 0 elif color == 'green': idx = 1 elif color == 'blue': idx = 2 for i in image: rgb = [] for j in i: rgb.append(j[idx]) # extract only color index value layer.append( rgb) return layer 46 47 # Test program image=[[[1,1,1], [2,2,2), (3,3,3]], [[4,4,4], (5,5,5), (6,6,6]], [[7,7,7], [8,8,8], [9,9,9]] ] print("crop( image, (0,0), 1,2)) of image ", image,"is", crop(image, (0,0),1,2)) image= [ [[1,1,2], [2,5,2]], [[3,4,4), (5,9,5]] ] print("color2gray(image) of image", image,"is", color2gray(image)) print("extract_layer(image, 'red') of image", image,"is", extract_layer(image, 'red'))
29 # To extract one color layer 20 dof nutnnct lavancimann colon). input crop(image, (0,0),1,2)) of image [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]], [[7, 7, 7], [8, 8, 8] <, 19, 9, 9]]] is [[[1, 1, 1], [2, 2, 2]]] color2gray(image) of image [[[1, 1, 2], [2, 5, 2]], [[3, 4, 4], [5, 9, 5]]] is [[1, 3], [3, 6]] extract_layer( image, 'red') of image [[[1, 1, 2], [2, 5, 2]], [[3, 4, 4], [5, 9, 5]]] is [[1, 2], [3, 5]] ...Program finished with exit code o Press ENTER to exit console. I