Python:在不依赖枕头库的情况下旋转图像?

时间:2018-12-03 20:11:10

标签: python image-editing

首先,我具有完整的python初学者水平,并且只有不到一个月的经验。

作为项目的一部分,我正在编写一个简单的程序,由此,我的两个主要目标是从头开始创建一个翻转和旋转图像的函数,以及另一个实质上改变图像的rgb值的函数(例如,使图像为灰度) )。将为用户提供一个选择,可以在其中选择要应用到图像的一种效果。我已经安装了枕头,还需要其他库吗?我想知道如何从头开始创建它们。

任何帮助将不胜感激

谢谢

编辑:为澄清起见,我将使用枕头,但我将自己创建旋转和灰度功能

2 个答案:

答案 0 :(得分:0)

枕头可让您访问图像的各个像素,这可以帮助您实现所需的功能。当然,诸如rotate()之类的库函数是执行此操作的更快方法,但是您只想探索和学习,这是编程乐趣的一半。

您可以创建一个新图像,然后在特定坐标处获取像素。

im = Image.new('RGBA', (250, 250))
im.getpixel((0, 0))

getpixel()将返回一个颜色信息元组,包含(红色,绿色,蓝色,阿尔法)

您还可以遍历图像并使用相同的颜色值元组“放入”新像素。

for x in range(200):
  for y in range(30):
    im.putpixel((x, y), (250, 0, 250))

完成后可以保存图像。

im.save('myImage.png')

以90度为增量进行旋转非常简单,您只需交换像素中的x和y值即可。

for x in range(200):
  for y in range(200):
    p = sourceImage.getpixel(x,y) # copy a pixel
    targetImage.getpixel(y,x,p)   # put it in the new image, rotated 90 deg

您的下一次访问将是查找计算机图形技术。

答案 1 :(得分:0)

您需要将图像分析为矩阵,然后交换列和行。这需要了解线性代数以进行优化。而且,如果您尝试对其进行暴力破解,则将等待大约30分钟以旋转每个图像(在此完成)。

Here is a look at inplace rotating。该程序的要旨是:

# Python3 program to rotate a matrix by 90 degrees
N = 4

# An Inplace function to rotate
# N x N matrix by 90 degrees in
# anti-clockwise direction
def rotateMatrix(mat):
  # Consider all squares one by one
  for x in range(0, int(N/2)):
     # Consider elements in group
     # of 4 in current square
     for y in range(x, N-x-1):
        # store current cell in temp variable
        temp = mat[x][y]

        # move values from right to top
        mat[x][y] = mat[y][N-1-x]

        # move values from bottom to right
        mat[y][N-1-x] = mat[N-1-x][N-1-y]

        # move values from left to bottom
        mat[N-1-x][N-1-y] = mat[N-1-y][x]

        # assign temp to left
        mat[N-1-y][x] = temp
# Function to pr the matrix
def displayMatrix( mat ):
  for i in range(0, N):
     for j in range(0, N):
        print (mat[i][j], end = ' ')
     print ("")

mat = [[0 for x in range(N)] for y in range(N)]  # Driver Code
# Test case 1
mat = [ [1, 2, 3, 4 ],
     [5, 6, 7, 8 ],
     [9, 10, 11, 12 ],
     [13, 14, 15, 16 ] ]
''' 
# Test case 2
mat = [ [1, 2, 3 ],
     [4, 5, 6 ],
     [7, 8, 9 ] ]

# Test case 3
mat = [ [1, 2 ],
     [4, 5 ] ]
'''

rotateMatrix(mat)
displayMatrix(mat)  # Print rotated matrix
# This code is contributed by saloni1297