Python實(shí)現(xiàn)多張圖片合成文字的效果
前言
前段時(shí)間看到有人問如何使用Python實(shí)現(xiàn)多張圖片組成文字的效果?覺得還挺有意思,于是嘗試做了一下,剛好趕上端午節(jié),所以打算從網(wǎng)上下載1000張王心凌的照片,組成端午安康的字樣,給大家送上祝福。
一、圖片批量下載
首先我們需要從百度下載大量王心凌的圖片,但是如果會(huì)去百度圖片里一張張右鍵下載,但這樣未免太麻煩了,所以打算直接用python寫一個(gè)批量下載圖片的代碼,輸入想要下載圖片的關(guān)鍵字,然后輸入想要下載圖片的數(shù)量,就可以成功下載圖片了!
代碼主要分成三個(gè)部分:
- 下載圖片
- 檢測(cè)圖片數(shù)量
- 查找相似圖片
1.下載圖片
def dowmloadPicture(html, keyword): global num # t =0 pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正則表達(dá)式找到圖片url print('找到關(guān)鍵詞:' + keyword + '的圖片,即將開始下載圖片...') for each in pic_url: print('正在下載第' + str(num + 1) + '張圖片,圖片地址:' + str(each)) try: if each is not None: pic = requests.get(each, timeout=7) else: continue except BaseException: print('錯(cuò)誤,當(dāng)前圖片無法下載') continue else: string = file + r'\\' + keyword + '_' + str(num) + '.jpg' fp = open(string, 'wb') fp.write(pic.content) fp.close() num += 1 if num >= numPicture: return
2.檢測(cè)圖片數(shù)量
def Find(url, A): global List print('正在檢測(cè)圖片總數(shù),請(qǐng)稍等.....') t = 0 i = 1 s = 0 while t < 1000: Url = url + str(t) try: # 這里搞了下 Result = A.get(Url, timeout=7, allow_redirects=False) except BaseException: t = t + 60 continue else: result = Result.text pic_url = re.findall('"objURL":"(.*?)",', result, re.S) # 先利用正則表達(dá)式找到圖片url s += len(pic_url) if len(pic_url) == 0: break else: List.append(pic_url) t = t + 60 return s
3.查找相似圖片
def dowmloadPicture(html, keyword): global num # t =0 pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正則表達(dá)式找到圖片url print('找到關(guān)鍵詞:' + keyword + '的圖片,即將開始下載圖片...') for each in pic_url: print('正在下載第' + str(num + 1) + '張圖片,圖片地址:' + str(each)) try: if each is not None: pic = requests.get(each, timeout=7) else: continue except BaseException: print('錯(cuò)誤,當(dāng)前圖片無法下載') continue else: string = file + r'\\' + keyword + '_' + str(num) + '.jpg' fp = open(string, 'wb') fp.write(pic.content) fp.close() num += 1 if num >= numPicture: return
使用效果:
二、圖片馬賽克
當(dāng)我們下載好了所需要的王心凌的照片,下一步我們需要用這些圖片組成我們需要的文字。
所以首先準(zhǔn)備一張要拼成的圖片,比如需要組成的文字,如端午安康,我們可以用 PowerPoint)制作一個(gè)喜歡的文字樣式,然后保存成jpg格式。
1.使用photomosaic庫(kù)實(shí)現(xiàn)圖片馬賽克
代碼如下所示:
import photomosaic as pm # 加載要拼成的圖片image(jpg 格式,圖片越大,得到的拼圖的每個(gè)小圖分辨率越高) image = pm.imread("1.jpg", as_gray=False) # 從指定文件夾加載圖片庫(kù)(需要比較多的圖片才能獲得較好的效果) pool = pm.make_pool("wxl/*.jpg") # 制作 50*50 的拼圖馬賽克 mosaic = pm.basic_mosaic(image, pool, (200, 200)) # 保存拼圖 pm.imsave("mosaic.jpg", mosaic)
不過由于這個(gè)庫(kù)版本問題,所以需要在庫(kù)函數(shù)里面做一點(diǎn)點(diǎn)修改才能成才運(yùn)行。
def crop_to_fit(image, shape): """ Return a copy of image resized and cropped to precisely fill a shape. To resize a colored 2D image, pass in a shape with two entries. When ``len(shape) < image.ndim``, higher dimensions are ignored. Parameters ---------- image : array shape : tuple e.g., ``(height, width)`` but any length <= ``image.ndim`` is allowed Returns ------- cropped_image : array """ # Resize smallest dimension (width or height) to fit. d = np.argmin(np.array(image.shape)[:2] / np.array(shape)) enlarged_shape = (tuple(np.ceil(np.array(image.shape[:len(shape)]) * shape[d]/image.shape[d])) + image.shape[len(shape):]) resized = resize(image, enlarged_shape, mode='constant', anti_aliasing=False) # Now the image is as large or larger than the shape along all dimensions. # Crop any overhang in the other dimension. crop_width = [] for actual, target in zip(resized.shape, shape): overflow = actual - target # Center the image and crop, biasing left if overflow is odd. left_margin = int(np.floor(overflow / 2)) right_margin = int(np.ceil(overflow / 2)) crop_width.append((left_margin, right_margin)) # Do not crop any additional dimensions beyond those given in shape. for _ in range(resized.ndim - len(shape)): crop_width.append((0, 0)) cropped = crop(resized, crop_width) return cropped
在裁剪圖片的時(shí)候輸入需要是int型,所以把left_margin和right_margin強(qiáng)制轉(zhuǎn)化成int型。
實(shí)現(xiàn)效果:
效果確實(shí)一般般,局部放大,可以觀察出,生成圖是由照片拼接而成的,所以整體大圖的清晰度也與小照片的數(shù)量有關(guān),也有可能是圖片分辨率大小以及組成圖片尺寸不一的原因,所以又嘗試了另一種方法。
2.計(jì)算顏色相似度實(shí)現(xiàn)圖片馬賽克
def readSourceImages(sourcepath,blocksize): print('開始讀取圖像') # 合法圖像列表 sourceimages = [] # 平均顏色列表 avgcolors = [] for path in tqdm(glob.glob("{}/*.jpg".format(sourcepath))): image = cv2.imread(path, cv2.IMREAD_COLOR) if image.shape[-1] != 3: continue image = cv2.resize(image, (blocksize, blocksize)) avgcolor = np.sum(np.sum(image, axis=0), axis=0) / (blocksize * blocksize) sourceimages.append(image) avgcolors.append(avgcolor) print('結(jié)束讀取') return sourceimages,np.array(avgcolors)
通過這個(gè)方法能夠獲取照片集中的每張照片與組成的大圖之間顏色的相似度,將相似的照片放到對(duì)應(yīng)的位置。
實(shí)現(xiàn)效果:
感覺效果比原來要好一些,但是還是不夠清晰。
到此這篇關(guān)于Python實(shí)現(xiàn)多張圖片合成文字的效果的文章就介紹到這了,更多相關(guān)Python多張圖片合成文字內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
實(shí)踐Vim配置python開發(fā)環(huán)境
這篇文章給大家分享了Vim配置python開發(fā)環(huán)境的實(shí)踐心得,大家可以跟著嘗試操作下。2018-07-07Python3.10?Generator生成器Coroutine原生協(xié)程詳解
這篇文章主要為大家介紹了Python3.10?Generator生成器Coroutine原生協(xié)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12解決python讀取幾千萬(wàn)行的大表內(nèi)存問題
今天小編就為大家分享一篇解決python讀取幾千萬(wàn)行的大表內(nèi)存問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06手把手教你pip配置國(guó)內(nèi)鏡像源(最新詳盡版)
pip是一個(gè)現(xiàn)代的,通用的Python包管理工具,提供了對(duì)Python包的查找、下載、安裝、卸載的功能,下面這篇文章主要給大家介紹了關(guān)于pip配置國(guó)內(nèi)鏡像源的相關(guān)資料,需要的朋友可以參考下2023-02-02Win10+python3.6+git運(yùn)行出現(xiàn)問題的解決
這篇文章主要介紹了Win10+python3.6+git運(yùn)行出現(xiàn)問題的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06何用Python實(shí)現(xiàn)一個(gè) “系統(tǒng)聲音” 的實(shí)時(shí)律動(dòng)掛件
這篇文章將給大家介紹了如何用 Python 實(shí)現(xiàn)一個(gè) “系統(tǒng)聲音” 的實(shí)時(shí)律動(dòng)掛件,采集后直接實(shí)時(shí)地在電腦上繪制波形動(dòng)畫,主要是用來作為 FL Studio 播放時(shí)的一個(gè)桌面小掛件,文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2024-01-01