Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate character Video by Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to generate character video by Python". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. Preface

I have also written articles to generate character video before, but I use the output of the command line window, the effect is not very good, and there is stutter. So I'm going to generate a mp4 character video directly. The general idea is the same as before: Python20 lines of code to characterize video.

Second, the operation image of OpenCV

Let's first look at some basic operations. First, we need to install OpenCV and execute the following statement:

Pip install opencv-python

And then you can use it.

2.1, read and display

Let's look directly at the code:

Import cv2# reads the picture img = cv2.imread ("1.jpg") # shows the picture cv2.imshow ("img", img) cv2.waitKey () cv2.destroyAllWindows ()

Where waitKey is the function waiting for input, because the imshow is displayed for a moment, so we need to call it. And destroyAllWindows is the release window.

2.2, grayscale conversion

Grayscale conversion is to convert a picture into black and white (gray), which makes it easy for us to deal with pixels. The code is as follows:

Import cv2img = cv2.imread ("1.jpg") # Gray conversion gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)

We can also read it directly in grayscale form:

Import cv2# reads img = cv2.imread ("1.jpg", 0) 2.4in grayscale form, gets the picture size and modifies the size

Let's look directly at the code:

Import cv2img = cv2.imread ("1.jpg", 0) # gets the height and width of the picture h, w = img.shape# zooms the picture res = cv2.resize (img, (w _ hand _ 2, h _ hand _ 2))

Because the shape property of img is a tuple, we can automatically unpack it directly.

Then call the cv2.resize function, and the first parameter is passed in the image, and the second parameter is passed in the modified size.

2.5. Draw text

To draw text, we need to call the cv2.putText function. The code is as follows:

Import cv2img = cv2.imread ('1.jpg') # drawing text cv2.putText (# picture drawn on the back img, # text to be drawn' Hello', 'coordinates of the lower left corner of the text (100,500), # font cv2.FONT_HERSHEY_SIMPLEX, # font size zoom 20, # text color (0,0,0) # text thickness 10)

We just need to pay attention to these parameters.

2.6. Read video

The operation of reading video is generally universal, and the code is as follows:

Import cv2# reads video cap = cv2.VideoCapture ('1.mp4') # get the frame rate of the video fps = cap.get (cv2.CAP_PROP_FPS) # Loop read each frame of the picture while True: # read the next frame ret, frame = cap.read () if not ret: break else: passcap.release ()

The frame of the video we obtained above, we need to use it when writing the video.

2.7. Write to video

The operation of writing video is also a regular code:

Import cv2fourcc = cv2.VideoWriter_fourcc (* 'mp4v') writer = cv2.VideoWriter (' 11.mp4legs, fourcc, fps, (w, h)) # write video writer.write (frame) * * write.release ()

With this knowledge, we can move on to the next step.

3. Mapping pixels to characters

For a picture with only one channel, we can think of it as a rectangle, and the smallest unit of this rectangle is one pixel. The process of characterization is the process of replacing pixels with characters. So we have to traverse every pixel of the image, but what character should we replace it with?

We have a reference table for color, and opencv cuts this parameter table into 256 pieces, representing different degrees, we can also make a reference table, but the contents of the table are not colors, but characters.

Here is our code for converting pixels to characters:

Def pixel2char (pixel): char_list = "@ # $% & erytuioplkszxcv=+---." Index = int (pixel / 256 * len (char_list)) return char_ list [index]

This character table can be defined by itself.

Fourth, generate character pictures

Now we just need to convert the pixels to characters one by one, the code is as follows:

Def get_char_img (img, scale=4, font_size=5): # resize the picture h, w = img.shape re_im = cv2.resize (img, (w//scale, h//scale)) # create a picture to fill in the character char_img = np.ones ((h//scale*font_size, w//scale*font_size)) Dtype=np.uint8) * 255 font = cv2.FONT_HERSHEY_SIMPLEX # traversing picture pixels for y in range (0, re_im.shape [0]): for x in range (0, re_im.shape [1]): char_pixel = pixel2char (re_ im [y] [x]) cv2.putText (char_img, char_pixel, (x*font_size, y*font_size), font, 0.5, (0) 0, 0) return char_img

Here we use a np.ones function, which we understand as generating a black image.

In addition to scale, how to multiply font_size for the generated size. Scale is the degree of reduction of the original image, because there are so many pixels, so we need to reduce the image first. In order to make our font display more clearly, we need to enlarge the generated character image.

Therefore, it is important to note that although the image we generate looks monotonous, when font_size is set to 5, the image is already larger. So when you generate a long-term video, it will take more time, and the resulting video will be larger.

Let's test the above function:

Import cv2import numpy as npdef pixel2char (pixel): char_list = "@ # $% & erytuioplkszxcv=+---." Index = int (pixel / 256* len (char_list)) return char_ list [index] def get_char_img (img, scale=4, font_size=5): # resize the picture h, w = img.shape re_im = cv2.resize (img, (w//scale, h//scale)) # create a picture to fill in the characters char_img = np.ones ((h//scale*font_size, w//scale*font_size)) Dtype=np.uint8) * 255 font = cv2.FONT_HERSHEY_SIMPLEX # traversing picture pixels for y in range (0, re_im.shape [0]): for x in range (0, re_im.shape [1]): char_pixel = pixel2char (re_ im [y] [x]) cv2.putText (char_img, char_pixel, (x*font_size, y*font_size), font, 0.5, (0) 0, 0) return char_imgif _ _ name__ = ='_ _ main__': img = cv2.imread ('dl.jpg', 0) res = get_char_img (img) cv2.imwrite (' d.jpgvideos, res) 5. Generate character video

With the above code, we can convert the entire video. The code for converting video to character video is as follows:

Def generate (input_video, output_video): # 1, read video cap = cv2.VideoCapture (input_video) # 2, get video frame rate fps = cap.get (cv2.CAP_PROP_FPS) # read the first frame, get the size of the picture converted into characters ret, frame = cap.read () char_img = get_char_img (cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY), 4) # create a VideoWriter Used to save video fourcc = cv2.VideoWriter_fourcc (* 'mp4v') writer = cv2.VideoWriter (output_video, fourcc, fps, (char_img.shape [1], char_ img.shape [0])) while ret: # reads the current frame of the video If not, jump out of the loop ret, frame = cap.read () if not ret: break # convert the current frame to a character graph gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY) char_img = get_char_img (gray, 4) # to BGR mode Easy to write video char_img = cv2.cvtColor (char_img, cv2.COLOR_GRAY2BGR) writer.write (char_img) writer.release ()

The complete code is as follows:

Import cv2import numpy as npdef pixel2char (pixel): char_list = "@ # $% & erytuioplkszxcv=+---." Index = int (pixel / 256* len (char_list)) return char_ list [index] def get_char_img (img, scale=4, font_size=5): # resize the picture h, w = img.shape re_im = cv2.resize (img, (w//scale, h//scale)) # create a picture to fill in the characters char_img = np.ones ((h//scale*font_size, w//scale*font_size)) Dtype=np.uint8) * 255 font = cv2.FONT_HERSHEY_SIMPLEX # traversing picture pixels for y in range (0, re_im.shape [0]): for x in range (0, re_im.shape [1]): char_pixel = pixel2char (re_ im [y] [x]) cv2.putText (char_img, char_pixel, (x*font_size, y*font_size), font, 0.5, (0) 0, 0) return char_imgdef generate (input_video, output_video): # 1. Read video cap = cv2.VideoCapture (input_video) # 2, get video frame rate fps = cap.get (cv2.CAP_PROP_FPS) # read the first frame Get the size of the image converted to characters ret, frame = cap.read () char_img = get_char_img (cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY), 4) # create a VideoWriter Used to save video fourcc = cv2.VideoWriter_fourcc (* 'mp4v') writer = cv2.VideoWriter (output_video, fourcc, fps, (char_img.shape [1], char_ img.shape [0])) while ret: # reads the current frame of the video If not, jump out of the loop ret, frame = cap.read () if not ret: break # convert the current frame to a character graph gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY) char_img = get_char_img (gray, 4) # to BGR mode Easy to write video char_img = cv2.cvtColor (char_img, cv2.COLOR_GRAY2BGR) writer.write (char_img) writer.release () if _ _ name__ ='_ _ main__': generate ('in.mp4',' out.mp4')

We just need to modify the parameters of generate.

This is the end of the content of "how Python generates character videos". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report