python draw.text_python 实现PIL模块在图片画线写字

本文介绍如何使用Python的PIL库在图片上画线和写字。通过示例代码展示了如何打开图片,创建绘图对象,设置线条和文字,并展示了在图像中人脸位置数据上画框的方法。
部署运行你感兴趣的模型镜像

图片上画线条

import sys

from PIL import Image,ImageDraw

im = Image.open("th.png")

draw = ImageDraw.Draw(im) #实例化一个对象

draw.line((0, 0) + im.size, fill=128, width=5) #线的起点和终点,线宽

draw.line((0, im.size[1], im.size[0], 0), fill=128)

draw.line((0,im.size[1]/2)+(im.size[0]/2,im.size[1]), fill=128, width=5)

im.show()

图片上写字

from PIL import Image, ImageDraw, ImageFont

# get an image

base = Image.open('th.jpg').convert('RGBA')

# make a blank image for the text, initialized to transparent text color

txt = Image.new('RGBA', base.size, (255,255,255,0))

# get a font 需要在C:\Windows\Fonts拷贝一份字体文件 当前脚本路径下

fnt = ImageFont.truetype('cambriai.ttf', 40)

# get a drawing context

d = ImageDraw.Draw(txt)

# draw text, half opacity

d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))

# draw text, full opacity

d.text((10,60), "World", font=fnt, fill=(255,255,255,255))

fillcolor = "#ff0000" #字体颜色

d.text((base.size[0]-20,10), "4", font=fnt, fill=fillcolor)

out = Image.alpha_composite(base, txt)

out.show()

参考官方文档 https://pillow.readthedocs.io/en/stable/reference/Image.html

补充知识:python对图像中的人脸进行画框(人脸的位置数据记录在记事本文件中)

我就废话不多说了,大家还是直接看代码吧!

import numpy as py

import os

import cv2 as cv

with open('labelFaceData.txt','r')as fp:#打开记录了数据的记事本文件

pictureNumber = 0#用来记录照片的数量

while 1:

count = 1

line = fp.readline()#读取文件中每一行的数据

if not line:#如果读取失败则退出

break

pictureNumber+=1#图片数加1

str1 = line.split()#用一个数组以字符串的形式储存文件中的数据

img = cv.inread(str[0])#str[0]中存放的是要读取的图片地址,用cv.inread读取它

faceNumber = (len(str1)-1)/16#用来记录人脸的总数

for i in reage(faceNumber):#用for循环对人脸进行画框

x = int(str1[count+1])#x,y,w,h为画框需要的点

y = int(str1[count+2])

w = int(str1[count+3])

h = int(str1[count+4])

cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),3,4,0)#用rectangle对图像进行画框

count+=16

#cv.namedWindow(str[0],0)

#cv.imshow(str[0],img);

#cv.waitKey(0)

cv.imwrite("./result/image1_"+str(pictureNumber)+".jpg",img)#保存图片

fp.close()

以上这篇python 实现PIL模块在图片画线写字就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持聚米学院。

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

import sys import numpy as np import pandas as pd from PIL import Image from PyQt5.QtCore import Qt from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier as KNN from PyQt5.Qt import QPainter, QPoint, QPen, QColor, QSize, QPixmap, QIcon, QCheckBox from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QPushButton, QSplitter, \ QComboBox, QLabel, QSpinBox, QFileDialog, QTextEdit, QWidget, QApplication print('加载中,请稍后。。。') df = pd.read_excel("/kaggle/input/111111/shoxiezitishibie.xlsx") x = df.drop(columns='对应数字') y = df['对应数字'] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1) knn = KNN(n_neighbors=1) knn.fit(x_train, y_train) def main(): # 界面菜单 class MainWidget(QWidget): def __init__(self, Parent=None): super().__init__(Parent) self.__InitData() # 先初始化数据,再初始化界面 self.__InitView() def __InitData(self): self.__paintBoard = PaintBoard(self) # 获取颜色列表(字符串类型) self.__colorList = QColor.colorNames() def __InitView(self): self.setFixedSize(640, 480) self.setWindowTitle("手写数字识别模型") # 窗口名 self.label_name = QLabel('39杨项钧', self) # 水印 self.label_name.setGeometry(150, 25, 100, 25) # 新建一个水平布局作为本窗体的主布局 main_layout = QHBoxLayout(self) # 设置主布局内边距以及控件间距为10px main_layout.setSpacing(10) # 在主界面左侧放置画板 main_layout.addWidget(self.__paintBoard) # 新建垂直子布局用于放置按键 sub_layout = QVBoxLayout() # 设置此子布局和内部控件的间距为10px sub_layout.setContentsMargins(10, 10, 10, 10) self.__btn_Clear = QPushButton("清空画板") self.__btn_Clear.setParent(self) # 设置父对象为本界面 # 将按键按下信号与画板清空函数相关联 self.__btn_Clear.clicked.connect(self.__paintBoard.Clear) sub_layout.addWidget(self.__btn_Clear) self.__btn_yuce = QPushButton("粗略预测") self.__btn_yuce.setParent(self) # 设置父对象为本界面 self.__btn_yuce.clicked.connect(lambda: self.yuce()) sub_layout.addWidget(self.__btn_yuce) self.__text_out = QTextEdit(self) self.__text_out.setParent(self) self.__text_out.setObjectName("预测结果为:") sub_layout.addWidget(self.__text_out) self.__btn_Quit = QPushButton("退出") self.__btn_Quit.setParent(self) # 设置父对象为本界面 self.__btn_Quit.clicked.connect(self.Quit) sub_layout.addWidget(self.__btn_Quit) self.__cbtn_Eraser = QCheckBox(" 使用橡皮擦") self.__cbtn_Eraser.setParent(self) self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked) sub_layout.addWidget(self.__cbtn_Eraser) splitter = QSplitter(self) # 占位符 sub_layout.addWidget(splitter) self.__label_penThickness = QLabel(self) self.__label_penThickness.setText("画笔粗细") self.__label_penThickness.setFixedHeight(20) sub_layout.addWidget(self.__label_penThickness) self.__spinBox_penThickness = QSpinBox(self) self.__spinBox_penThickness.setMaximum(50) self.__spinBox_penThickness.setMinimum(10) self.__spinBox_penThickness.setValue(30) # 默认粗细为30 self.__spinBox_penThickness.setSingleStep(2) # 最小变化值为2 self.__spinBox_penThickness.valueChanged.connect( self.on_PenThicknessChange) # 关联spinBox值变化信号和函数on_PenThicknessChange sub_layout.addWidget(self.__spinBox_penThickness) self.__label_penColor = QLabel(self) self.__label_penColor.setText("画笔颜色") self.__label_penColor.setFixedHeight(20) sub_layout.addWidget(self.__label_penColor) self.__comboBox_penColor = QComboBox(self) self.__fillColorList(self.__comboBox_penColor) # 用各种颜色填充下拉列表 self.__comboBox_penColor.currentIndexChanged.connect( self.on_PenColorChange) # 关联下拉列表的当前索引变更信号与函数on_PenColorChange sub_layout.addWidget(self.__comboBox_penColor) main_layout.addLayout(sub_layout) # 将子布局加入主布局 def __fillColorList(self, comboBox): # 颜色表 index_black = 0 index = 0 for color in self.__colorList: if color == "black": index_black = index index += 1 pix = QPixmap(70, 20) pix.fill(QColor(color)) comboBox.addItem(QIcon(pix), None) comboBox.setIconSize(QSize(70, 20)) comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) comboBox.setCurrentIndex(index_black) def on_PenColorChange(self): # 改变笔色 color_index = self.__comboBox_penColor.currentIndex() color_str = self.__colorList[color_index] self.__paintBoard.ChangePenColor(color_str) def on_PenThicknessChange(self): # 改变笔粗细 penThickness = self.__spinBox_penThickness.value() self.__paintBoard.ChangePenThickness(penThickness) def on_btn_Save_Clicked(self): # 保存 savePath = QFileDialog.getSaveFileName(self, '保存绘画', '.\\', '*.png') print(savePath) if savePath[0] == "": print("保存取消") return image = self.__paintBoard.GetContentAsQImage() image.save(savePath[0]) def on_cbtn_Eraser_clicked(self): # 橡皮擦 if self.__cbtn_Eraser.isChecked(): self.__paintBoard.EraserMode = True # 进入橡皮擦模式 else: self.__paintBoard.EraserMode = False # 退出橡皮擦模式 def Quit(self): self.close() # 退出 def yuce(self): # #标准化图片 获取Y savePath = "./test.png" image = self.__paintBoard.GetContentAsQImage() image.save(savePath) img = Image.open(savePath) img = img.resize((32, 32)) # 调整尺寸 img = img.convert("1") # 灰度化 img_new = img.point(lambda x: 1 if x > 128 else 0) arr = np.array(img_new) arr_new = arr.reshape(1, -1) answer = knn.predict(arr_new) self.__text_out.setText(str(answer[0])) print('图中数字:' + str(answer[0])) # 手写画板 class PaintBoard(QWidget): def __init__(self, Parent=None): super().__init__(Parent) self.__InitData() # 先初始化数据,再初始化界面 self.__InitView() def __InitData(self): self.__size = QSize(320, 320) # 新建QPixmap作为画板,尺寸为__size self.__board = QPixmap(self.__size) self.__board.fill(Qt.black) # 用黑色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__painter = QPainter() # 新建绘图工具 self.__thickness = 30 # 默认画笔粗细为30px self.__penColor = QColor("white") # 设置默认画笔颜色为白色 self.__colorList = QColor.colorNames() # 获取颜色列表 def __InitView(self): # 设置界面的尺寸为__size self.setFixedSize(self.__size) def Clear(self): # 清空画板 self.__board.fill(Qt.black) self.update() self.__IsEmpty = True def ChangePenColor(self, color="black"): # 改变画笔颜色 self.__penColor = QColor(color) def ChangePenThickness(self, thickness=10): # 改变画笔粗细 self.__thickness = thickness def IsEmpty(self): # 返回画板是否为空 return self.__IsEmpty def GetContentAsQImage(self): # 获取画板内容(返回QImage) image = self.__board.toImage() return image def paintEvent(self, paintEvent): # 绘图事件 # 绘图时必须使用QPainter的实例,此处为__painter # 绘图在begin()函数与end()函数间进行 # begin(param)的参数要指定绘图设备,即把图画在哪里 # drawPixmap用于绘制QPixmap类型的对象 self.__painter.begin(self) # 0,0为绘图的左上角起点的坐标,__board即要绘制的图 self.__painter.drawPixmap(0, 0, self.__board) self.__painter.end() def mousePressEvent(self, mouseEvent): # 鼠标按下时,获取鼠标的当前位置保存为上一次位置 self.__currentPos = mouseEvent.pos() self.__lastPos = self.__currentPos def mouseMoveEvent(self, mouseEvent): # 鼠标移动时,更新当前位置,并在上一个位置和当前位置间画线 self.__currentPos = mouseEvent.pos() self.__painter.begin(self.__board) if self.EraserMode == False: # 非橡皮擦模式 self.__painter.setPen(QPen(self.__penColor, self.__thickness)) # 设置画笔颜色,粗细 else: # 橡皮擦模式下画笔为纯白色,粗细为20 self.__painter.setPen(QPen(Qt.black, 20)) # 画线 self.__painter.drawLine(self.__lastPos, self.__currentPos) self.__painter.end() self.__lastPos = self.__currentPos self.update() # 更新显示 def mouseReleaseEvent(self, mouseEvent): self.__IsEmpty = False # 画板不再为空 app = QApplication(sys.argv) mainWidget = MainWidget() # 新建一个主界面 print('加载成功') # 显示主界面 mainWidget.show() sys.exit(app.exec_()) # 进入消息循环 if __name__ == '__main__': main()
最新发布
06-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值