0

I'm trying to flip an image vertically without using any default flip() or similar functions.I tried to iterate along the pixels and by using loops tried to reverse it so i can flip the image vertically.

image=cv2.imread('boat.jpg',1)
height,width,channel=image.shape
list1=[]
list2=[]
for i in range(height):
    for j in range(width):
        list1.append(image[i,j])
for a in range(len(list1)-1,-1,-1):
     list2.append(list1[a])
b=0
for i in range(height):
    for j in range(width):
        image[i,j]=list2[b]
        b+=1

But the flipped image is looking like this: https://ibb.co/KKVkd2d What am i doing wrong?

7
  • Since you're already using OpenCV, why not just use flip for this? I'd be something like flipped_image = cv2.flip(image, 0). Do you explicitly want to use a loop to do the flipping manually? Commented Nov 12, 2019 at 8:07
  • @martineau Please don't further use the cv2 tag, since it's pending removal (see tag wiki excerpt). python and opencv tags are preferred here. Commented Nov 12, 2019 at 8:09
  • Yeah i want to create my own flip function without using cv2.flip() method or any other methods which is similar. Commented Nov 12, 2019 at 8:16
  • 1
    Beside the typo in len(list) works fine here Commented Nov 12, 2019 at 8:36
  • I corrected it but the output image is still wrong. Commented Nov 12, 2019 at 8:49

1 Answer 1

1

To flip vertically you have to reverse rows in array - first row has to be last, last row has to be first. You don't have to move pixels in rows.

import cv2
import numpy 

image = cv2.imread('boat.jpg', 1)

image = numpy.array(list(reversed(image)))

cv2.imshow('window', image)

cv2.waitKey(0)

BTW: if you want to flip horizontally then you have to reverse pixels in rows.

import cv2
import numpy 

image = cv2.imread('boat.jpg', 1)

image = numpy.array([list(reversed(row)) for row in image])

cv2.imshow('window', image)

cv2.waitKey(0)
Sign up to request clarification or add additional context in comments.

3 Comments

I would use cv2.flip. Decomposing the image into lists of rows of pixels and reversing the list is more computationally intrusive. techtutorialsx.com/2019/04/21/python-opencv-flipping-an-image
OP in this comment said that he want to do it without cv2.flip :)
Oh I missed the comments. I just looked at the question. Thanks!