Grid an image with opencv python with respect to image size

Viewed 5088

I am trying to have a grid over a picture using the cv2.line method. Right now, I am doing a for loop that goes to the width of the image so I can put a couple of vertical lines across my image. However, after I run and compile the code, I get a window with a blue picture

img = cv2.imread("target.PNG")

height, width, channels = img.shape
for x in range(0, width -1, 1):
     cv2.line(img, (x, 0), (x, height), (255, 0, 0), 1, 1)

cv2.imshow('Hehe', img)
key = cv2.waitKey(0)

Right now, this is for the vertical lines only. I will later add the horizontal ones once I get this working. It outputs a full blue screen rather than grids. I tried playing with the number according to the beginning and end of (x,y) coordinates.

1 Answers

You are drawing blue lines to entire image without skipping any pixel, set step size of your range to something like 20. For example:

img = cv2.imread("target.PNG")
GRID_SIZE = 20

height, width, channels = img.shape
for x in range(0, width -1, GRID_SIZE):
     cv2.line(img, (x, 0), (x, height), (255, 0, 0), 1, 1)

cv2.imshow('Hehe', img)
key = cv2.waitKey(0)
Related