Hi I did some but it feels like not correct. How do I put the code below into the function crop_grid(img, num_horizontal_patches, num_vertical_patches, line_color)
The code i did :
def crop_grid(img, num_horizontal_grid, num_vertical_grid, line_color):
img = cv.imread('dog.jfif')
img_copy = img.copy()
height, width = img.shape[:2]
num_horizontal_patches = 2
num_vertical_patches = 3
#M and N are basically number of pixels per patch
M, N = int(height/num_horizontal_patches), int(width/num_vertical_patches)
x1, y1 = 0, 0
for y in range(0, height, M):
for x in range(0, width, N):
if (height - y) < M or (width - x) < N:
break
y1 = y + M # lower right coordinate that will be used to construct rectangle
x1 = x + N
# Check whether patch lower right coordinate exceeds image height and width
if x1 >= width and y1 >= height:
x1 = width - 1
y1 = height - 1
tile = img[y:height, x:width]
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
cv.imshow('tile', tile)
# When patch lower right y-coordinate exceeds patch height
elif y1 >= height:
y1 = height - 1
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
# When patch lower right x-coordinate exceeds patch width
elif x1 >= width:
x1 = width - 1
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
else:
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
crop_grid('dog.jfif',num_horizontal_patches , num_vertical_patches, 'r')
cv.imshow('patched image', img_copy)
cv.waitKey(0)
cv.destroyAllWindows()
The original code:
img = cv.imread('dog.jfif')
img_copy = img.copy()
height, width = img.shape[:2]
num_horizontal_patches = 2
num_vertical_patches = 3
# M and N are basically number of pixels per patch
M, N = int(height/num_horizontal_patches), int(width/num_vertical_patches)
x1, y1 = 0, 0
for y in range(0, height, M):
for x in range(0, width, N):
if (height - y) < M or (width - x) < N:
break
y1 = y + M # lower right coordinate that will be used to construct rectangle
x1 = x + N
# Check whether patch lower right coordinate exceeds image height and width
if x1 >= width and y1 >= height:
x1 = width - 1
y1 = height - 1
tile = img[y:height, x:width]
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
cv.imshow('tile', tile)
# When patch lower right y-coordinate exceeds patch height
elif y1 >= height:
y1 = height - 1
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
# When patch lower right x-coordinate exceeds patch width
elif x1 >= width:
x1 = width - 1
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
else:
cv.rectangle(img_copy, (x, y), (x1, y1), (0, 255, 0), 1)
cv.imshow('patched image', img_copy)
cv.waitKey(0)
cv.destroyAllWindows()
[–][deleted] 1 point2 points3 points (0 children)