当前位置:网站首页>Picture batch download + picture mosaic: multiple pictures constitute the Dragon Boat Festival Ankang!
Picture batch download + picture mosaic: multiple pictures constitute the Dragon Boat Festival Ankang!
2022-06-10 01:12:00 【Yunlord】
hello ! Hello everyone , I am a Yunlord,CSDN2021 The third place in the field of artificial intelligence of blog star in , Years of experience in artificial intelligence learning , A man with a strange interest 【 Bloggers in the field of artificial intelligence 】!
Good at image recognition 、 Natural language processing and other artificial intelligence fields , At the same time proficient in python, And continue to expand their own areas of learning , Dedicated to the promotion and application of interesting and interesting technologies !!!
If there are friends who are interested in novel technologies , Welcome to continue to pay attention Yunlord️️️
Preface
Some time ago I saw someone ask how to use Python Realization Multiple pictures form text The effect of ? I think it's very interesting , So I tried to do it , Just in time for the Dragon Boat Festival , So I plan to download it from the Internet 1000 A photo of Wang Xinling , The Dragon Boat Festival is composed of the words "well-being" , Send you blessings .

One 、 Image bulk download
First of all, we need to download a large number of Wang Xinling's pictures from Baidu , But if you will go to Baidu pictures and right-click to download them , But it's too much trouble , So I plan to use it directly python Write a batch download image code , Enter the keyword you want to download the picture , Then enter the number of images you want to download , You can download the pictures successfully !
The code is mainly divided into three parts :
- Download the pictures
- Number of detected pictures
- Look for similar pictures
1. Download the pictures
def dowmloadPicture(html, keyword):
global num
# t =0
pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # First, use regular expressions to find pictures url
print(' Find keywords :' + keyword + ' Pictures of the , About to start downloading pictures ...')
for each in pic_url:
print(' Downloading section ' + str(num + 1) + ' A picture , Picture address :' + str(each))
try:
if each is not None:
pic = requests.get(each, timeout=7)
else:
continue
except BaseException:
print(' error , The current picture cannot be downloaded ')
continue
else:
string = file + r'\\' + keyword + '_' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numPicture:
return2. Number of detected pictures
def Find(url, A):
global List
print(' Detecting total number of pictures , One moment please .....')
t = 0
i = 1
s = 0
while t < 1000:
Url = url + str(t)
try:
# There's been a little bit of
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) # First, use regular expressions to find pictures url
s += len(pic_url)
if len(pic_url) == 0:
break
else:
List.append(pic_url)
t = t + 60
return s3. Look for similar pictures
def dowmloadPicture(html, keyword):
global num
# t =0
pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # First, use regular expressions to find pictures url
print(' Find keywords :' + keyword + ' Pictures of the , About to start downloading pictures ...')
for each in pic_url:
print(' Downloading section ' + str(num + 1) + ' A picture , Picture address :' + str(each))
try:
if each is not None:
pic = requests.get(each, timeout=7)
else:
continue
except BaseException:
print(' error , The current picture cannot be downloaded ')
continue
else:
string = file + r'\\' + keyword + '_' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numPicture:
returnUse effect :


Two 、 Picture mosaic
When we have downloaded the required photos of Wang Xinling , Next we need to use these pictures to form the text we need .
So first prepare a picture to be assembled , For example, the words that need to be composed , Such as the Dragon Boat Festival , We can use PowerPoint) Make a favorite text style , And save it as jpg Format .

1. Use photomosaic Library to achieve picture mosaic
The code is as follows :
import photomosaic as pm
# Load the picture to be assembled image(jpg Format , The bigger the picture , The higher the resolution of each small picture of the puzzle )
image = pm.imread("1.jpg", as_gray=False)
# Load the picture library from the specified folder ( You need more pictures to get better results )
pool = pm.make_pool("wxl/*.jpg")
# Make 50*50 A mosaic of jigsaw puzzles
mosaic = pm.basic_mosaic(image, pool, (200, 200))
# Save puzzle
pm.imsave("mosaic.jpg", mosaic)
However, due to the library version problem , So you need to make a little change in the library function to run successfully .
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 croppedWhen cutting the picture, the input needs to be int type , So the left_margin and right_margin Force into int type .
Realization effect :

The effect is really average , Local magnification , It can be observed that , The generated image is composed of photos , Therefore, the sharpness of the overall large picture is also related to the number of small photos , It is also possible that the resolution and size of the picture are different , So I tried another method .
2. Calculate color similarity to realize picture mosaic
def readSourceImages(sourcepath,blocksize):
print(' Start reading image ')
# List of legal images
sourceimages = []
# Average color list
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(' End read ')
return sourceimages,np.array(avgcolors)This method can obtain the color similarity between each photo in the photo set and the large picture , Put similar photos in the corresponding positions .
Realization effect :

I feel the effect is better than before , But it is not clear enough .
Another article 2 ten thousand 8 How to use thousands of pictures python Make up a self portrait of your girlfriend ! Rendering made :

Felt the effect was much better , Maybe it's because the resolution of text and image is not high enough .
summary
This time How to realize the effect of text composed of multiple pictures by using batch downloading of pictures and picture mosaic , I hope you can support me a lot , If you have any questions, you can leave a message in the comment area to discuss .
Reference resources :
Python A series of crawler tutorials crawl a batch of Baidu pictures
How to use Python To make a , Many, many pictures make up the effect of text ?
边栏推荐
- 剑指 Offer II 011. 0 和 1 个数相同的子数组
- Tensorflow new document publishing: add CLP, dtensor State of the art models are ready
- 洛谷P2657 [SCOI2009]windy数 题解 数位DP
- 内网渗透简洁笔记
- Force deduction solution summary 497 random points in non overlapping rectangles
- Summary - 【 JVM 】
- datagrip的两个问题
- Can the online security of futures account opening be guaranteed? Which futures company is good?
- Mysql——》varchar
- Analyse du code source de la Bibliothèque open source de Tencent libco CO CO - Process
猜你喜欢

Sword finger offer II 010 Subarray with and K

Set of common numbers

线性规划和对偶规划学习总结

Republish experiment

Flutter ITMS-90338: Non-public API usage - Frameworks/webview_ flutter_ wkwebview. framework

花了两小时体验IDEA最新史诗皮肤

JVM records a CPU surge

Where should middle-aged test development engineers go? The unknown is tomorrow, break the label

The latest version of Alibaba development manual is released in 2022!!!

Spent two hours experiencing the latest epic skin of idea
随机推荐
上位机开发——Modbus到底有多快
消防应急照明和疏散指示系统在某洁净医药的设计与应用
洛谷P2657 [SCOI2009]windy数 题解 数位DP
BGP protocol experiment
写入速度提升数十倍,TDengine 在拓斯达智能工厂解决方案上的应用
Republish experiment
别再重复造轮子了,推荐使用 Google Guava 开源工具类库,真心强大!
Alleviate and repair Android studio Caton, kotlin code prompt is slow
nn. Modulelist() and nn Sequential()
Hcip first job
nn.ModuleList()与nn.Sequential()
Esri整合LightBox数据以扩展加拿大境内的地理编码
Two problems of DataGrid
Can the online security of futures account opening be guaranteed? Which futures company is good?
PCI bar register explanation (two examples)
从转载阿里开源项目 Egg.js 技术文档引发的“版权纠纷”,看宽松的 MIT 许可该如何用?
Summary of learning linear programming and dual programming
Mysql——》查看索引的大小
MySQL - separate database and table
进阶自动化测试的看过来,一文7个阶段5000字带你全面了解自动化测试