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



首先,我对python已经达到了完全的初学者水平,只有不到一个月的经验。

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

如有任何帮助,将不胜感激

感谢

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

Pillow提供了对图像各个像素的访问,可以帮助您实现所需。当然,像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

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

您需要将图像分析为矩阵,然后交换列和行。这需要理解用于优化的线性代数。如果你试图使用暴力,你将等待大约30分钟来旋转每个图像(已经完成了(。

下面是就地旋转。该程序的要点是:

# 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

最新更新