python – 使用PIL修剪扫描图像?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用PIL修剪扫描图像?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2423字,纯文字阅读大概需要4分钟。
内容图文
![python – 使用PIL修剪扫描图像?](/upload/InfoBanner/zyjiaocheng/699/d3d790649e19487fb77e129bab9da6ef.jpg)
修剪使用扫描仪输入的图像的方法是什么,因此具有大的白/黑区域?
解决方法:
熵解决方案似乎有问题且计算过于密集.为什么边缘检测不到?
我刚刚编写了这个python代码来为自己解决同样的问题.我的背景是肮脏的白色,所以我使用的标准是黑暗和颜色.我通过为每个像素取最小的R,B或B值来简化这个标准,因此黑色或饱和的红色都突出相同.我还使用了每行或每列的许多最暗像素的平均值.然后我从每个边缘开始,一直工作直到我越过一个门槛.
这是我的代码:
#these values set how sensitive the bounding box detection is
threshold = 200 #the average of the darkest values must be _below_ this to count (0 is darkest, 255 is lightest)
obviousness = 50 #how many of the darkest pixels to include (1 would mean a single dark pixel triggers it)
from PIL import Image
def find_line(vals):
#implement edge detection once, use many times
for i,tmp in enumerate(vals):
tmp.sort()
average = float(sum(tmp[:obviousness]))/len(tmp[:obviousness])
if average <= threshold:
return i
return i #i is left over from failed threshold finding, it is the bounds
def getbox(img):
#get the bounding box of the interesting part of a PIL image object
#this is done by getting the darekest of the R, G or B value of each pixel
#and finding were the edge gest dark/colored enough
#returns a tuple of (left,upper,right,lower)
width, height = img.size #for making a 2d array
retval = [0,0,width,height] #values will be disposed of, but this is a black image's box
pixels = list(img.getdata())
vals = [] #store the value of the darkest color
for pixel in pixels:
vals.append(min(pixel)) #the darkest of the R,G or B values
#make 2d array
vals = np.array([vals[i * width:(i + 1) * width] for i in xrange(height)])
#start with upper bounds
forupper = vals.copy()
retval[1] = find_line(forupper)
#next, do lower bounds
forlower = vals.copy()
forlower = np.flipud(forlower)
retval[3] = height - find_line(forlower)
#left edge, same as before but roatate the data so left edge is top edge
forleft = vals.copy()
forleft = np.swapaxes(forleft,0,1)
retval[0] = find_line(forleft)
#and right edge is bottom edge of rotated array
forright = vals.copy()
forright = np.swapaxes(forright,0,1)
forright = np.flipud(forright)
retval[2] = width - find_line(forright)
if retval[0] >= retval[2] or retval[1] >= retval[3]:
print "error, bounding box is not legit"
return None
return tuple(retval)
if __name__ == '__main__':
image = Image.open('cat.jpg')
box = getbox(image)
print "result is: ",box
result = image.crop(box)
result.show()
内容总结
以上是互联网集市为您收集整理的python – 使用PIL修剪扫描图像?全部内容,希望文章能够帮你解决python – 使用PIL修剪扫描图像?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。