我想以与标准CAPTCHA扭曲字体相同的方式扭曲一些图像。我该如何在Python中实现?我应该使用哪些库/算法?有任何概念证明吗?免责声明:在提出这个问题之前,我已经谷歌搜索了一段时间,但我找不到令人满意的答案。由于我是新手,无法提供任何代码证明我的“研究努力”...
我认为你正在寻找PyCaptcha http://svn.navi.cx/misc/trunk/pycaptcha/
这是实际扭曲的代码: http://svn.navi.cx/misc/trunk/pycaptcha/Captcha/Visual/Distortions.py
使用PIL的变换函数来完成工作,就像这样:
image.transform(image.size, Image.MESH, mesh, self.filtering)
其余的代码基本上是用来生成所使用的网格的。
扭曲图像意味着将一个像素与其相邻像素中的任何一个进行混淆。
如果算法混淆了远离的像素,则扭曲程度较高,如果混淆了附近的像素,则扭曲程度较低。
我之前几天处理过类似的问题,我使用了PIL。
import math
from PIL import Image
img = Image.open('image.jpg') #open a image
width ,height = img.size
img_data = img.load() #loading it, for fast operation
output = Image.new('RGB',img.size,"gray") #New image for putput
output_img = output.load() #loading this also, for fast operation
pix=[0, 0]
delta_x = 40 #you can lower the delta for high distortion
delta_y = 90 #or you can higher the delta for low distortion
for x in range(width):
for y in range(height):
#following expression calculates the snuffling
x_shift, y_shift = ( int(abs(math.sin(x)*width/delta_x)) ,
int(abs(math.tan(math.sin(y)))*height/delta_y))
#checking bounds
if x + x_shift < width:
pix[0] = x + x_shift
else:
pix[0] = x
if y + y_shift < height :
pix[1] = y + y_shift
else:
pix[1] = y
# do the shuffling
output_img[x,y] = img_data[tuple(pix)]
#Saving the image
output.save('output.jpeg')
x_shift, y_shift = ( int(abs(math.sin(x)*width/delta_x)) ,
int(abs(math.tan(math.sin(y)))*height/delta_y))
matplotlib
中的示例;我将常规的x/y重新定位到一个不规则间距,从而扭曲了图像。对于验证码的外观,您需要想出一些更有创意的重新映射方法。import pylab as P
import numpy as N
# http://matplotlib.org/examples/images_contours_and_fields
# /pcolormesh_levels.html
dx, dy = 0.05, 0.05
y, x = N.mgrid[slice(1, 5 + dy, dy),
slice(1, 5 + dx, dx)]
z = N.sin(x) ** 10 + N.cos(10 + y * x) * N.cos(x)
#distort from regular pixels to something else...
x1 = N.exp(x)
y1 = N.sqrt(y)
P.figure()
P.pcolormesh(x,y,z)
P.figure()
P.pcolormesh(x1,y1,z)
P.show()
您可以适应 django-simple-captcha 的代码,其中在 https://raw.github.com/mbi/django-simple-captcha/master/captcha/views.py 中存在一个名为 captcha_image
的函数,您可以轻松地进行修改。