自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

用 Python 制作可視化 GUI 界面,一鍵實現(xiàn)證件照背景顏色的替換

開發(fā) 后端
今天,我們來分享一下如何通過Python的十來行代碼來替換證件照的背景顏色,那么在最后,小編也會將上述的流程制作成一個GUI界面來方便大家使用。

關于界面的大致模樣其實和先前的相差不大,大家應該都看過上一篇的內(nèi)容。

界面大體的樣子

整體GUI的界面如下圖所示:

用戶在使用的時候可以選擇將證件照片替換成是“白底背景”或者是“紅底背景”,那么在前端的界面上傳完成照片之后,后端的程序便會開始執(zhí)行該有的操作。

去除掉背景顏色

首先我們需要將照片的背景顏色給去除掉,這里用到的是第三方的接口removebg,官方鏈接是:

我們在完成賬號的注冊之后,訪問下面的鏈接獲取api_key:https://www.remove.bg/api#remove-background

下面便是相對應的程序代碼了,如下:

def remove_bg(self):
api_keys = "自己注冊的api_key"
rmbg = RemoveBg(api_keys, "error.log")
rmbg.remove_background_from_img_file(imgNamepath)

添加上我們想要的顏色

在完成去除掉證件照片的背景顏色之后,我們再添加上我們想要的背景顏色即可,例如我們想要添加上“紅色”的背景顏色,代碼如下:

no_bg_image = Image.open(in_path)
x, y = no_bg_image.size
new_image = Image.new('RGBA', no_bg_image.size, color="red")
new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
new_image.save(output_path)

這次我們在GUI界面中用到的顯示圖片的控件是graphicsView組件,我們在點擊“選擇圖片”的按鈕之后,在上傳圖片之后,需要在graphicsView窗口當中將圖片顯示出來,代碼如下:

def openImage(self):
global imgNamepath # 這里為了方便別的地方引用圖片路徑,將其設置為全局變量
imgNamepath, imgType = QFileDialog.getOpenFileName(self.ui, "選擇圖片", "D:\\", "*.png;;*.jpg;;All Files(*)")
# 通過文件路徑獲取圖片文件,并設置圖片長寬為label控件的長、寬
img = QtGui.QPixmap(imgNamepath).scaled(self.ui.graphicsView.size(), aspectMode=Qt.KeepAspectRatioByExpanding)
print("img: ", img.width(), img.height())
self.ui.graphicsView.setFixedSize(img.width(), img.height())
# 在label控件上顯示選擇的圖片
item = QGraphicsPixmapItem(img)
scene = QGraphicsScene()
scene.addItem(item)
self.ui.graphicsView.setScene(scene)
self.ui.graphicsView.repaint()
# 顯示所選圖片的路徑
self.ui.lineEdit.setText(imgNamepath)

最后我們來看一下整體的效果

責任編輯:龐桂玉 來源: AI科技大本營
相關推薦

2022-01-25 12:51:58

Python代碼證件照

2024-09-04 15:09:58

AI模型

2021-12-30 12:02:52

Python可視化代碼

2022-08-24 13:39:46

PandasGUIExcel

2021-03-31 13:28:17

開源工具Python編程語言

2020-02-27 08:59:11

DebugCode開源工具

2017-10-14 13:54:26

數(shù)據(jù)可視化數(shù)據(jù)信息可視化

2022-08-26 09:15:58

Python可視化plotly

2019-08-06 10:35:25

Python時間序列可視化

2022-08-23 12:32:37

Python可視化圖表

2022-12-31 18:22:23

2024-08-02 10:30:39

StreamlitPython庫數(shù)據(jù)驅(qū)動

2020-03-11 14:39:26

數(shù)據(jù)可視化地圖可視化地理信息

2012-06-27 09:34:15

隱私泄漏黑客

2018-03-14 14:28:20

Python數(shù)據(jù)分析可視化

2022-09-29 11:16:21

Python數(shù)據(jù)可視化

2014-12-31 16:48:43

Touch touchevent多點觸摸

2021-10-14 08:40:58

前端技術數(shù)據(jù)可視化

2020-11-02 13:54:41

Python可視化決策樹

2010-07-30 14:00:41

Flex組件
點贊
收藏

51CTO技術棧公眾號