PIL----crop()和paste()

本文介绍如何使用Python Imaging Library (PIL)去除图像底部的非注册版提示文本。通过使用crop和paste函数,实现自动裁剪并覆盖指定区域,以移除不需要的文字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PIL(Python Imaging Library)是python语言中对图像处理方面的一个开源库,其主要功能模块为Image,对于Image模块,可以使用

Python代码   收藏代码
  1. from PIL import Image  

或者

Python代码   收藏代码
  1. import Image  

 由于使用了试用版的chartdir库,在生成图片的时候下面会出现一行提示是非注册版的文字,看起来不太舒服。


 

所以想使用PIL自动地将下面一行去掉,查阅了一下PIL的文档,最后决定使用PIL的crop和paste函数实现功能

实现的代码如下:

Python代码   收藏代码
  1. import Image  
  2. import sys  
  3.   
  4. if len(sys.argv)<2:  
  5.     print '%s <image file>' % __file__  
  6.     sys.exit()  
  7. else:  
  8.     filename = sys.argv[1]  
  9.       
  10. img = Image.open(filename)  
  11.   
  12. width = img.size[0]  
  13. height = img.size[1]  
  14.   
  15. img1 = img.crop((0,0,width,9))  
  16.   
  17. #img1 = Image.new('RGBA',(width,10))  
  18. img.paste(img1,(0,height-9))  
  19. img.save(filename)  
  20.   
  21. img = Image.open(filename)  
  22. img.show()  

 这可以使用的方法有两种,第一种是以及被注释掉的方法,即生成一个新的Image,调用Image.new方法。然后将该image粘贴到需要修改的图片上。另外一种为了保持图片的前后背景色一致,从图片的最前头拷贝一部分图片(使用crop函数),然后在粘贴到需要修改的图片上,来完成最下端文字的覆盖。

 

crop函数带的参数为(起始点的横坐标,起始点的纵坐标,宽度,高度)

paste函数的参数为(需要修改的图片,粘贴的起始点的横坐标,粘贴的起始点的纵坐标)

 

下面是处理结果之后的图片:



 

PS.使用chartdir生成图片的Python脚本

Python代码   收藏代码
  1. #!-*- encoding: utf-8 -*-  
  2.   
  3. #!/usr/bin/python  
  4. from pychartdir import *  
  5.   
  6. # The data for the bar chart  
  7. data = [45056063080011001350160019502300270032003800]  
  8.   
  9. # The labels for the bar chart  
  10. labels = ["一月""二月""三月""四月""五月""六月""七月""八月""九月",  
  11.     "十月""十一月""十二月"]  
  12.   
  13. # Create a XYChart object of size 600 x 360 pixels  
  14. c = XYChart(600360)  
  15.   
  16. # Add a title to the chart using 18pts Times Bold Italic font  
  17. c.addTitle("卖家月份销售图表""simsun.ttc"18)  
  18.   
  19. # Set the plotarea at (60, 40) and of size 500 x 280 pixels. Use a vertical gradient  
  20. # color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and  
  21. # grid lines to white (ffffff).  
  22. c.setPlotArea(6040500280, c.linearGradientColor(6040602800xeeeeff,  
  23.     0x0000cc), -10xffffff0xffffff)  
  24.   
  25. # Add a multi-color bar chart layer using the supplied data. Use soft lighting effect  
  26. # with light direction from left.  
  27. c.addBarLayer3(data).setBorderColor(Transparent, softLighting(Left))  
  28.   
  29. # Set x axis labels using the given labels  
  30. c.xAxis().setLabels(labels)  
  31.   
  32. # Draw the ticks between label positions (instead of at label positions)  
  33. c.xAxis().setTickOffset(0.5)  
  34.   
  35. # Add a title to the y axis with 10pts Arial Bold font  
  36. c.yAxis().setTitle("人民币 (元)""simsun.ttc"10)  
  37.   
  38. # Set axis label style to 8pts Arial Bold  
  39. c.xAxis().setLabelStyle("simsun.ttc"8)  
  40. c.yAxis().setLabelStyle("simsun.ttc"8)  
  41.   
  42. # Set axis line width to 2 pixels  
  43. c.xAxis().setWidth(2)  
  44. c.yAxis().setWidth(2)  
  45.   
  46. # Output the chart  
  47. c.makeChart("1.png")  
### 使用CutMixMosaic进行数据增强 #### CutMix 数据增强技术 CutMix 是一种通过将一幅图像的一部分替换为另一幅图像相应部分并调整标签来创建新样本的方法。这种方法不仅增加了训练集的多样性,还帮助模型学习到不同类别的特征组合。 对于实现 CutMix 的过程如下: 1. 选取两张不同的原始图像及其对应的标签; 2. 在其中一张图像上随机选定一块矩形区域; 3. 将该区域内像素值替换成第二张图片相同位置处的内容; 4. 对应的目标向量也做相应的线性插值操作以反映新的合成情况; Python 实现示例: ```python import numpy as np from PIL import Image, ImageDraw def cutmix(image_a, image_b, label_a, label_b): """Apply CutMix augmentation on two images.""" width, height = image_a.size # Randomly choose a bounding box within the first image. cx = np.random.randint(width) cy = np.random.randint(height) bbx_w = np.random.uniform() * min(cx, width-cx) bbx_h = np.random.uniform() * min(cy, height-cy) x1 = int(max(0, cx-bbx_w)) y1 = int(max(0, cy-bbx_h)) x2 = int(min(width ,cx+bbx_w)) y2 = int(min(height,cy+bbx_h)) mixed_image = image_a.copy() region_from_imgb = image_b.crop((x1,y1,x2,y2)) mixed_image.paste(region_from_imgb,(x1,y1)) lam = (x2-x1)*(y2-y1)/(width*height) new_label = float(lam)*label_b+(1-float(lam))*label_a return mixed_image, new_label ``` #### Mosaic 数据增强技术 Mosaic 方法则是更进一步地融合多张(通常是四张)小图形成单一大图用于训练。这种方式使得每批次内含有更多信息量,在一定程度上缓解了过拟合现象的发生几率。 具体做法是在预处理阶段拼接四个相邻的小块构成一个新的大尺寸输入给网络。这有助于提升检测效果特别是针对目标尺度变化较大的场景下表现尤为明显。 以下是基于 PyTorch Albumentations 库的应用实例: ```python import albumentations as A from torchvision.transforms.functional import to_tensor class LoadMosaicImageAndLabels(object): def __init__(self, dataset, mosaic=True, degrees=0., translate=.1, scale=(.9, 1.1), shear=2.0, perspective=0.0, border=(0, 0)): self.dataset = dataset ... def __call__(self, index=-1): labels4 = [] s = self.img_size yc, xc = [int(random.uniform(-x, 2*s+x)) for x in self.border] # 中心坐标偏移范围 indices = [index] + random.choices(range(len(self)), k=3) # 取当前索引其他三个随机索引 for i, idx in enumerate(indices): img, _, (h, w) = load_image(self, idx) # place img in img4 if i == 0: # top left img4 = np.full( (s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # fill value x1a, y1a, x2a, y2a = max(xc-w, 0), max(yc-h, 0), xc, yc x1b, y1b, x2b, y2b = w - (x2a-x1a), h-(y2a-y1a), w,h elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc-h, 0), min(xc+w, s * 2), yc x1b, y1b, x2b, y2b = 0, h-(y2a-y1a), min(w, x2a-x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc-w, 0), yc, xc, min(s*2, yc+h) x1b, y1b, x2b, y2b = w-(x2a-x1a), 0, max(xc, w), min(y2a-y1a, h) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc+w, s*2), min(s*2, yc+h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a-x1a), min(y2a-y1a, h) img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] padw = x1a - x1b pady = y1a - y1b labels = targets[idx].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, pady) # normalized xywh to pixel xyxy format labels4.append(labels) # Concat/clip labels if len(labels4): labels4 = np.concatenate(labels4, 0) ... transformed = transform(**{'image':img4,'bboxes':labels4}) img_mosiac = transformed['image'] boxes = transformed['bboxes'] return img_mosiac, boxes ``` 上述代码片段展示了如何利用 Python 编程语言以及相关库来实施这两种先进的视觉任务前处理技巧[^2][^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值