2

there are many methods to rotate img by 90 degree using OpenCV or PIL, how to do it by self-design code without using any libs? I have tried in the way of rotating a matrix, but the RGB elements make it fail

Aleebaba UCSD
  • 55
  • 1
  • 6
  • How are you reading or writing the image file without using any libs? Unless you are using simple file formats (like the NetPBM family) image file reading & writing without libs is tedious and easy to mess up. – PM 2Ring Oct 08 '17 at 22:49
  • reading and writing can use lib function, but the rotating process cannot – Aleebaba UCSD Oct 08 '17 at 23:06

2 Answers2

0

Did you try this logic?

Rotating a 2D pixel array by 90 degrees

Usually c++ is a good way to form coding without calling any libs

arisAbCy
  • 71
  • 7
0

You can rotate a grid of pixels by 90° by a combination of transposition and reflection. You can do this in pure Python by using zip to transpose, and reversed to reflect.

Here's a short demo that does a 90° clockwise rotation.

# Some fake pixels
data = [
    [(100, 101, 102), (105, 106, 107), (110, 111, 112), (115, 116, 117)], 
    [(120, 121, 122), (125, 126, 127), (130, 131, 132), (135, 136, 137)], 
    [(140, 141, 142), (145, 146, 147), (150, 151, 152), (155, 156, 157)], 
    [(160, 161, 162), (165, 166, 167), (170, 171, 172), (175, 176, 177)], 
    [(180, 181, 182), (185, 186, 187), (190, 191, 192), (195, 196, 197)], 
]

new = [list(reversed(t)) for t in zip(*data)]
for row in new:
    print(row)

output

[(180, 181, 182), (160, 161, 162), (140, 141, 142), (120, 121, 122), (100, 101, 102)]
[(185, 186, 187), (165, 166, 167), (145, 146, 147), (125, 126, 127), (105, 106, 107)]
[(190, 191, 192), (170, 171, 172), (150, 151, 152), (130, 131, 132), (110, 111, 112)]
[(195, 196, 197), (175, 176, 177), (155, 156, 157), (135, 136, 137), (115, 116, 117)]

But seriously, it's faster (and simpler) to do this sort of thing with a library, unless the images are really small. If you don't want to use PIL, you can do it with Numpy.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182