In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article Xiaobian for you to introduce in detail "python video conversion byte problem how to solve", the content is detailed, the steps are clear, the details are handled properly, I hope this "python video conversion byte problem how to solve" article can help you solve doubts, the following follow the editor's ideas slowly in depth, together to learn new knowledge.
Steps
Convert a video into a picture frame by frame
Convert a picture into a character painting
Play character paintings in order
1. Prepare
Install the Python-OpenCV library
Install Numpy Scientific Computing Library
Use the module library
Import timeimport cv2import osfrom PIL import Image, ImageDraw, ImageFontimport numpy as npimport os
Then create a new python code document and add the import statement above and below at the beginning
two。 Materials
The material comes to a video file. I use zimeng.mp4 here. Download it and put the code in the same directory.
You can also change it to your own. The suggestion is to choose a short video as much as possible when you study. Ten seconds and ten seconds will do. It is convenient to adjust and try.
In addition, choose a video with high contrast. Otherwise, color characters are needed to perform well enough. I'll try it sometime.
3. Read video by frame
Now continue to add code to achieve the first step: read the video by frame.
The following function accepts the size information of the video path and character video and returns an img list, where the img is a grayscale image of the specified size.
The first step is to capture the picture.
Def video_img (file='zimeng.mp4'): # create a new folder under the current directory folder_path = "img_bear/" if folder_path: pass else: os.makedirs (folder_path) # load the video vc = cv2.VideoCapture (file) # determine whether the loaded video can open ret = vc.isOpened () # loop Read video frame num = 0 while ret: num = num + 1 # to read a single picture The value of ret is True or Flase,frame indicates the read image ret. Frame = vc.read () if ret: # is stored as image cv2.imwrite ('img_bear/' + str (num) +' .jpg') Frame) # output image name print ('img_bear/' + str (num) +' .jpg') # wait for the user to press the button to trigger within a given time (in ms), 1ms cv2.waitKey (1) else: break # Video release vc.release () time.sleep (0.5) video_image (num)
If the operation is reported correctly, there will be no problem.
The comments in the code should be clear. Move on to the next step.
The second step is to do grayscale processing on the picture.
The video is converted into an image, and this step is to convert the image into a character painting.
The above function, with an img object as an argument, goes to the corresponding character drawing
Def video_image (num=''): # create character picture folder folder_path = "bear/" if folder_path: pass else: os.makedirs (folder_path) for i in range (1 Num): filename = 'img_bear/' + str (I) +' .jpg'im = Image.open (filename) # returns an Image object width = im.size [0] heigth = im.size [1] print ('W:% d, H:% d'% (im.size [0]) Im.size [1]) # character list ascii_char = list ("$@ B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\ | () 1 {} []?-_ + ~ iridi :,\ "^'. ") # determine whether a picture exists if os.path.exists (filename): # convert the picture to a grayscale image, and resize img_array = np.array (Image.open (filename). Resize ((160,160), Image.ANTIALIAS) .convert ('L')) # create a new picture object img = Image.new ('Image.new, (width) Heigth), 255) draw_object = ImageDraw.Draw (img) # set font font = ImageFont.truetype ('consola.ttf', 10, encoding='unic') # add the corresponding characters for j in range according to the grayscale value: for k in range: X, y = k * 8 J * 8 index = int (img_ array [j] [k] / 4) draw_object.text ((x, y), ascii_char [index], font=font, fill=0) name = 'bear/' + str (I) +' .jpg 'print (name) # Save character picture img.save (name) 'JPEG') time.sleep (0.5) video (num)
Step 3: character to video
Now that I've written so much code, it's finally going to work. Now is the most exciting step: play the character painting.
Oddly, I encapsulated it into a function. The above function takes a list of character drawings and plays them.
Def video (num): filename = 'img_bear/' + str (1) +' .jpg'im = Image.open (filename) # returns an Image object width = im.size [0] heigth = im.size [1] # set video encoder, here use MJPG encoder fourcc = cv2.VideoWriter_fourcc (* 'MJPG') # to output video parameter settings Contains video file name, encoder, frame rate, video width and height (here parameters need to be the same as character picture size) videoWriter = cv2.VideoWriter ('bear_character.avi', fourcc, 20.0, (width, heigth)) for i in range (1 Num): filename= 'bear/'+str (I) +' .jpg'# determine whether the picture exists if os.path.exists (filename): img = cv2.imread (filename=filename) # wait for the user to press the key to trigger within a given time (in ms) 100ms cv2.waitKey (100) # write the picture to the video videoWriter.write (img) print (str (I) + '.jpg' + 'creative video') # Video release videoWriter.release () time.sleep (1) # Delete the picture remove_img () remove_img_bear ()
The following complete code
It may take a long time. It takes about 500 seconds for me to use the sample video.
Ctrl+f10 executes the corresponding file
The complete code is added.
Execute to generate pictures, generate grayscale images, and finally generate byte video to delete redundant files.
Said too much nonsense is: finally, we need to delete some temporary files and folders.
Import timeimport cv2import osfrom PIL import Image, ImageDraw The first step of ImageFontimport numpy as npimport os# is to capture the image def video_img (file='zimeng.mp4'): # create a new folder under the current directory folder_path = "img_bear/" if folder_path: pass else: os.makedirs (folder_path) # to load the video vc = cv2.VideoCapture (file) # to determine whether the loaded video can be opened Ret = vc.isOpened () # read video frame num = 0 while ret: num = num + 1 # to read a single picture The value of ret is True or Flase,frame indicates the read image ret. Frame = vc.read () if ret: # is stored as image cv2.imwrite ('img_bear/' + str (num) +' .jpg') Frame) # output image name print ('img_bear/' + str (num) +' .jpg') # wait for the user to press the key to trigger within a given time (in ms) 1ms cv2.waitKey (1) else: break # Video release vc.release () time.sleep (0.5) video_image (num) # step 2 perform grayscale processing on the picture def video_image (num=''): # create a character picture folder folder_path = "bear/" if folder_path: pass else: Os.makedirs (folder_path) for i in range (1 Num): filename = 'img_bear/' + str (I) +' .jpg'im = Image.open (filename) # returns an Image object width = im.size [0] heigth = im.size [1] print ('W:% d, H:% d'% (im.size [0], im.size [1])) # this character table is used for new character frames Corresponding to 256pixels, the more characters and different styles, the finer the character frame is ascii_char = list ("$@ B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\ | () 1 {} []?-_ + ~ iridi. :,\ "^'. ") # determine whether a picture exists if os.path.exists (filename): # convert the picture to a grayscale image, and resize img_array = np.array (Image.open (filename). Resize ((160,160), Image.ANTIALIAS) .convert ('L')) # create a new picture object img = Image.new ('Image.new, (width) Heigth), 255) draw_object = ImageDraw.Draw (img) # set font font = ImageFont.truetype ('consola.ttf', 10, encoding='unic') # add the corresponding characters for j in range according to the grayscale value: for k in range: X, y = k * 8 J * 8 index = int (img_ array [j] [k] / 4) draw_object.text ((x, y), ascii_char [index], font=font, fill=0) name = 'bear/' + str (I) +' .jpg 'print (name) # Save character picture img.save (name) 'JPEG') time.sleep (0.5) video (num) # third step character to video def video (num): filename =' img_bear/' + str (1) + '.jpg' im = Image.open (filename) # returns an Image object width = im.size [0] heigth = im.size [1] # set the video encoder Here we use the MJPG encoder fourcc = cv2.VideoWriter_fourcc (* 'MJPG') # output video parameter settings, including video file name, encoder, frame rate, video width and height (here the parameters need to be the same as the character image size) videoWriter = cv2.VideoWriter (' bear_character.avi', fourcc, 20.0, (width, heigth)) for i in range (1) Num): filename= 'bear/'+str (I) +' .jpg'# determine whether the picture exists if os.path.exists (filename): img = cv2.imread (filename=filename) # wait for the user to press the key to trigger within a given time (in ms) 100ms cv2.waitKey (100) # write the picture to the video videoWriter.write (img) print (str (I) + '.jpg' + 'roomproof') # Video release videoWriter.release () time.sleep (1) # Delete the picture remove_img () remove_img_bear () # delete the def remove_ from the original picture Img (): files = os.getcwd () # files saves the current execution directory file_name = files + "/ img_bear" del_list = os.listdir (file_name) for f in del_list: file_path = os.path.join (file_name) F) print (file_path) if os.path.isfile (file_path): os.remove (file_path) print ('successfully deleted file:') else: print ('not found this file:') # Grayscale image deletion def remove_img_bear (): files = os.getcwd () # files saves the current The execution directory of file_name = files + "/ bear" del_list = os.listdir (file_name) for f in del_list: file_path = os.path.join (file_name F) print (file_path) if os.path.isfile (file_path): os.remove (file_path) print ('successfully deleted file:') else: print ('file not found:') def main (): video_img ('video.mp4') if _ _ name__ = = "_ _ main__": main ()
Further optimization
At this point, the core functions are basically complete.
But when you think about it, there's a lot more you can do:
What is the specified interval and frame rate to be converted?
Each conversion takes a long time, can you play it at the same time? Or save the data after conversion, and read the cache directly the next time you play it.
Take a look at the effect picture.
After reading this, the article "how to solve the byte problem of python video conversion" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.