Opencv Python snowflake falling effect

ShellCollector 2021-04-06 23:50:35
opencv python snowflake falling effect


source :https://blog.csdn.net/LaoYuanPython/article/details/115298737

First look at the target effect :

 picture

 

Material preparation  &  Thought analysis

This snowflake comes from the following picture ( file name :f:\pic\snow.jpg):
 picture

The background can be any picture , Here is an image of Mount Everest that the old ape found on the Internet ( file name :f:\pic\Qomolangma2.jpg):

 picture

Snowflakes are falling in the sky against the background of Mount Everest , Good mood ?

Realize the idea

To make snowflakes fall , A single display of a single picture is certainly not enough , You need to loop through the pictures , And every time the picture is shown , Generate new snowflakes and update the position of existing snowflakes in the picture , This requires precise management of the position of each snowflake in the picture .

Snowflakes in nature are different in size , So in order to improve the fidelity , Also need to make the snowflake size in a certain range of random changes and rotation .

Keep producing snowflakes of different sizes , If we transform snowflakes every time we produce snowflakes, it is a waste of system resources , So in order to improve processing performance , Only at the beginning of the program initialization, a batch production of various sizes 、 All kinds of snowflakes with different rotation angles , When subsequent programs generate snowflakes , Take one of the batch generated snowflakes directly as the snowflake to be generated , Instead of starting with the basic snowflake image each time .

 

Key implementation code

1、 Generate all kinds of snowflake shapes

def initSnowShapes(): """ Read in the snowflake picture from the file , And different scales of reduction and different angles of rotation, so as to generate different shapes of snowflakes , These snowflake shapes are saved in the global list snowShapesList """ global snowShapesList imgSnow = readImgFile(r'f:\pic\snow.jpg')  imgSnow = cv2.resize(imgSnow, None, fx=0.2, fy=0.2) # The snowflakes in the picture file are bigger , It needs to be shrunk to look like a natural snowflake  minFactor,maxFactor = 50,100 # The size of snowflakes is imgSnow Of 0.5-1 Times 
 for factor in range(minFactor,maxFactor,5): # Each time 5% size  f = factor*0.01 imgSnowSize = cv2.resize(imgSnow, None, fx=f, fy=f) for ange in range(0,360,5):# snow 0-360 Rotate between  imgRotate = rotationImg(imgSnowSize,ange)            snowShapesList.append(imgRotate)

2、 Produce a row of snowflakes ​​​​​​​

def generateOneRowSnows(width,count): """ Produce a row of snowflake objects , Each snowflake randomly from snowShapesList Take a 、 The abscissa position is random 、 The initial ordinate is 0 :param width: Background image width  :param count: The number of snowflakes in hope  :return: A list containing information about multiple snowflake objects generated , Each element of the list represents a snowflake object , The snowflake object contains three pieces of information , stay snowShapesList The index number of 、 initial x coordinate 、 initial y coordinate ( It is fixed as 0) """ global snowShapesList line = [] picCount = len(snowShapesList)  for loop in range(count): imgId = random.randint(0,picCount-1) xPos = random.randint(0,width-1) line.append((imgId,xPos,0)) return line

3、 Merge all the snowflake objects into the background image ​​​​​​​

def putSnowObjectToImg(img): """ Will all snowObjects The snowflake object in the image fusion img in , When merging y The coordinates move down a certain height at random ,x The coordinates move randomly in a small range  """ global snowShapesList,snowObjects horizontalMaxDistance,verticalMaxDistance = 5,20 # The maximum value of left-right drift in horizontal direction and the maximum value of falling in vertical direction  snowObjectCount = len(snowObjects) rows,cols = img.shape[0:2] imgResult = np.array(img) for index in range(snowObjectCount-1,-1,-1): imgObj = snowObjects[index] # Each element is (imgId,x,y) if imgObj[2]>rows: # If the starting ordinate of the snowflake has exceeded the height of the background image ( That's to the bottom of the background image ), The snowflake object needs to be disabled  del(snowObjects[index]) else: imgSnow = snowShapesList[imgObj[0]] x,y = imgObj[1:] # Take the last position of the snowflake  x = x+random.randint(-1*horizontalMaxDistance,horizontalMaxDistance) # The abscissa moves randomly left and right in a certain range  y = y+random.randint(1,verticalMaxDistance) # The ordinate falls randomly in a certain range  snowObjects[index] = (imgObj[0],x,y) # Update snowflake object information  imgResult = addImgToLargeImg(imgSnow,imgResult,(x,y),180) # All the snowflake object images are fused into the background image according to their positions  return imgResult # Back to the fused image 

4、 The main function

The main function reads in the background image , Initialize the snowflake shape list , Then the cycle produces a new row of snowflakes from the top , And all the snowflake objects are fused into the background image after adjusting the position dynamically , Every time 200 One millisecond cycle , Until you press ESC sign out .

​​​​​​​

def main(): global snowShapesList,snowObjects bg = readImgFile(r'f:\pic\Qomolangma2.jpg') initSnowShapes() rows,cols = bg.shape[:2] maxObjsPerRow = int(cols/100)
 while(True): snowObjects += generateOneRowSnows(cols,random.randint(0,maxObjsPerRow)) result = putSnowObjectToImg(bg) cv2.imshow('result',result) ch = cv2.waitKey(200)        if ch==27:break

 

Main program complete code and snowflake falling effect

5.1、 Main program complete code ​​​​​​​

# -*- coding: utf-8 -*-import cv2,randomimport numpy as np
from opencvPublic import addImgToLargeImg,readImgFile,rotationImgsnowShapesList = [] # Snowflake shape list snowObjects=[] # All the snowflake objects to be shown in the picture 
def initSnowShapes(): """ Read in the snowflake picture from the file , And different scales of reduction and different angles of rotation, so as to generate different shapes of snowflakes , These snowflake shapes are saved in the global list snowShapesList """ global snowShapesList imgSnow = readImgFile(r'f:\pic\snow.jpg') imgSnow = cv2.resize(imgSnow, None, fx=0.2, fy=0.2) # The snowflakes in the picture file are bigger , It needs to be shrunk to look like a natural snowflake  minFactor,maxFactor = 50,100 # The size of snowflakes is imgSnow Of 0.5-1 Times 
 for factor in range(minFactor,maxFactor,5): # Each time 5% size  f = factor*0.01 imgSnowSize = cv2.resize(imgSnow, None, fx=f, fy=f) for ange in range(0,360,5):# snow 0-360 Rotate between , Every time the rotation angle increases 5° imgRotate = rotationImg(imgSnowSize,ange) snowShapesList.append(imgRotate)
def generateOneRowSnows(width,count): """ Produce a row of snowflake objects , Each snowflake randomly from snowShapesList Take a 、 The abscissa position is random 、 The initial ordinate is 0 :param width: Background image width  :param count: The number of snowflakes in hope  :y: Corresponding to the current vertical coordinate line  :return: A list containing information about multiple snowflake objects generated , Each element of the list represents a snowflake object , The snowflake object contains three pieces of information , stay snowShapesList The index number of 、 initial x coordinate 、 initial y coordinate ( It is fixed as 0) """ global snowShapesList line = [] picCount = len(snowShapesList) for loop in range(count): imgId = random.randint(0,picCount-1) xPos = random.randint(0,width-1) line.append((imgId,xPos,0)) return line
def putSnowObjectToImg(img): """ Will all snowObjects The snowflake object in the image fusion img in , When merging y The coordinates move down a certain height at random ,x The coordinates move randomly in a small range  """ global snowShapesList,snowObjects horizontalMaxDistance,verticalMaxDistance = 5,20 # The maximum value of left-right drift in horizontal direction and the maximum value of falling in vertical direction  snowObjectCount = len(snowObjects) rows,cols = img.shape[0:2] imgResult = np.array(img) for index in range(snowObjectCount-1,-1,-1): imgObj = snowObjects[index] # Each element is (imgId,x,y) if imgObj[2]>rows: # If the starting ordinate of the snowflake has exceeded the height of the background image ( That's to the bottom of the background image ), The snowflake object needs to be disabled  del(snowObjects[index]) else: imgSnow = snowShapesList[imgObj[0]] x,y = imgObj[1:] # Take the last position of the snowflake  x = x+random.randint(-1*horizontalMaxDistance,horizontalMaxDistance) # The abscissa moves randomly left and right in a certain range  y = y+random.randint(1,verticalMaxDistance) # The ordinate falls randomly in a certain range  snowObjects[index] = (imgObj[0],x,y) # Update snowflake object information  imgResult = addImgToLargeImg(imgSnow,imgResult,(x,y),180) # All the snowflake object images are fused into the background image according to their positions  return imgResult # Back to the fused image 
def main(): global snowShapesList,snowObjects
 initSnowShapes() bg = readImgFile(r'f:\pic\Qomolangma2.jpg') rows,cols = bg.shape[:2] maxObjsPerRow = int(cols/100)
 while(True): snowObjects += generateOneRowSnows(cols,random.randint(0,maxObjsPerRow)) result = putSnowObjectToImg(bg) cv2.imshow('result',result) ch = cv2.waitKey(200) if ch==27:break
main()

 

summary

This paper introduces how to use OpenCV-Python The idea of making snowflake falling effect with specific image as background 、 The key functions and the complete code of the main program . Snowflake falling effect is actually an image fusion operation , As long as you master the basic knowledge of image fusion and the realization idea after design , It's fast to realize , The effect is also very good . Combined with the above code , You can also adjust the size of snowflakes and the density of snowflakes .

Attention should be paid to the above implementation process :

1、 Snowflake pictures are usually more effective than pictures need to be , How to shrink to the right size needs to try more , Here is the effect of just starting to abbreviate the original image by half .

 picture

You can see that the effect is not very satisfactory .

2、 Control the speed and amplitude of snowflakes moving left and right and falling down , Too fast 、 Too slow and too large or too small is not like falling in a snowflake .

版权声明
本文为[ShellCollector]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210406232411309V.html

  1. Do you need to learn database to learn Python!
  2. Python描述 LeetCode 80. 删除有序数组中的重复项 II
  3. C++/python描述 AcWing 94. 递归实现排列型枚举
  4. C++/python描述 AcWing 92. 递归实现指数型枚举
  5. Python描述 LeetCode 88. 合并两个有序数组
  6. 苏州大学计算机考研 复试机试真题2013-2021真题及Python题解
  7. Python描述 LeetCode 781. 森林中的兔子
  8. 字典和json的区别是什么?Python学习
  9. Python describes leetcode 80. Removing duplicate items from ordered arrays II
  10. C + + / Python description acwing 94. Recursive implementation of permutation enumeration
  11. C + + / Python description acwing 92. Recursive implementation of exponential enumeration
  12. Python describes leetcode 88. Merging two ordered arrays
  13. Real computer test questions 2013-2021 of computer postgraduate entrance examination of Soochow University and python solutions
  14. The rabbit in the forest
  15. Python中的魔法属性
  16. What's the difference between dictionary and JSON? Python learning
  17. Magic properties in Python
  18. 字典和json的区别是什么?Python学习
  19. What's the difference between dictionary and JSON? Python learning
  20. python刷题-字母图形
  21. Python brush questions - letter graphics
  22. Python数据分析入门(七):Pandas层级索引
  23. Introduction to Python data analysis (7): Pandas hierarchical index
  24. Python 操作腾讯云短信(sms)详细教程
  25. Python operation Tencent cloud SMS (SMS) detailed tutorial
  26. Python数据可视化,完整版实操指南 !
  27. Python data visualization, full version of the practical guide!
  28. 上手Pandas,带你玩转数据(2)-- 使用pandas从多种文件中读取数据
  29. 上手Pandas,带你玩转数据(1)-- 实例详解pandas数据结构
  30. Using pandas to read data from various files
  31. Hands on pandas, take you to play with data (1) -- detailed explanation of pandas data structure with examples
  32. Pandas数据结构基础用法
  33. Basic usage of pandas data structure
  34. Python读取ini配置文件,保存到对象属性
  35. Python reads the INI configuration file and saves it to the object properties
  36. Foundation of Python: classes in Python
  37. python刷题-闰年判断
  38. python刷题-01字串
  39. How to judge leap year
  40. Python brush title-01 string
  41. 安装python
  42. 按尺寸切片pandas数据集DataFrame到多个文件
  43. Install Python
  44. Slice the pandas dataset dataframe to multiple files by size
  45. python 求最大值、最小值、平均值
  46. Finding maximum, minimum and average in Python
  47. 认识Python解释器和PyCharm编辑器
  48. Know Python interpreter and pycharm editor
  49. Python 小数据池和代码块缓存机制
  50. Python small data pool and code block caching mechanism
  51. python刷题-序列求和
  52. python刷题-圆的面积
  53. Sequence summation in Python
  54. The area of a circle
  55. Python functions, advanced syntax and usage
  56. Teach you to crawl novels in Python! Who can pay for novels these days!
  57. Python入门学习之:10分钟1500访问量
  58. Introduction to Python: 1500 visits in 10 minutes
  59. 数据分析之Pandas合并操作总结
  60. OpenCV-Python 雪花飘落特效