Python實現(xiàn)多張圖片合成文字的效果
前言
前段時間看到有人問如何使用Python實現(xiàn)多張圖片組成文字的效果?覺得還挺有意思,于是嘗試做了一下,剛好趕上端午節(jié),所以打算從網(wǎng)上下載1000張王心凌的照片,組成端午安康的字樣,給大家送上祝福。

一、圖片批量下載
首先我們需要從百度下載大量王心凌的圖片,但是如果會去百度圖片里一張張右鍵下載,但這樣未免太麻煩了,所以打算直接用python寫一個批量下載圖片的代碼,輸入想要下載圖片的關(guān)鍵字,然后輸入想要下載圖片的數(shù)量,就可以成功下載圖片了!
代碼主要分成三個部分:
- 下載圖片
- 檢測圖片數(shù)量
- 查找相似圖片
1.下載圖片
def dowmloadPicture(html, keyword):
global num
# t =0
pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正則表達式找到圖片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('錯誤,當前圖片無法下載')
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.檢測圖片數(shù)量
def Find(url, A):
global List
print('正在檢測圖片總數(shù),請稍等.....')
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) # 先利用正則表達式找到圖片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) # 先利用正則表達式找到圖片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('錯誤,當前圖片無法下載')
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
使用效果:


二、圖片馬賽克
當我們下載好了所需要的王心凌的照片,下一步我們需要用這些圖片組成我們需要的文字。
所以首先準備一張要拼成的圖片,比如需要組成的文字,如端午安康,我們可以用 PowerPoint)制作一個喜歡的文字樣式,然后保存成jpg格式。

1.使用photomosaic庫實現(xiàn)圖片馬賽克
代碼如下所示:
import photomosaic as pm
# 加載要拼成的圖片image(jpg 格式,圖片越大,得到的拼圖的每個小圖分辨率越高)
image = pm.imread("1.jpg", as_gray=False)
# 從指定文件夾加載圖片庫(需要比較多的圖片才能獲得較好的效果)
pool = pm.make_pool("wxl/*.jpg")
# 制作 50*50 的拼圖馬賽克
mosaic = pm.basic_mosaic(image, pool, (200, 200))
# 保存拼圖
pm.imsave("mosaic.jpg", mosaic)不過由于這個庫版本問題,所以需要在庫函數(shù)里面做一點點修改才能成才運行。
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
在裁剪圖片的時候輸入需要是int型,所以把left_margin和right_margin強制轉(zhuǎn)化成int型。
實現(xiàn)效果:

效果確實一般般,局部放大,可以觀察出,生成圖是由照片拼接而成的,所以整體大圖的清晰度也與小照片的數(shù)量有關(guān),也有可能是圖片分辨率大小以及組成圖片尺寸不一的原因,所以又嘗試了另一種方法。
2.計算顏色相似度實現(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)
通過這個方法能夠獲取照片集中的每張照片與組成的大圖之間顏色的相似度,將相似的照片放到對應(yīng)的位置。
實現(xiàn)效果:

感覺效果比原來要好一些,但是還是不夠清晰。
到此這篇關(guān)于Python實現(xiàn)多張圖片合成文字的效果的文章就介紹到這了,更多相關(guān)Python多張圖片合成文字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3.10?Generator生成器Coroutine原生協(xié)程詳解
這篇文章主要為大家介紹了Python3.10?Generator生成器Coroutine原生協(xié)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
Win10+python3.6+git運行出現(xiàn)問題的解決
這篇文章主要介紹了Win10+python3.6+git運行出現(xiàn)問題的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
何用Python實現(xiàn)一個 “系統(tǒng)聲音” 的實時律動掛件
這篇文章將給大家介紹了如何用 Python 實現(xiàn)一個 “系統(tǒng)聲音” 的實時律動掛件,采集后直接實時地在電腦上繪制波形動畫,主要是用來作為 FL Studio 播放時的一個桌面小掛件,文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2024-01-01

