First, let's take a look at the final effect of this article :
To generate QR code, you can directly use the ready-made python
library :qrcode
:
pip install qrcode
Use qrcode
Generate qr code :
def mk_qr(txt, dst): img = qrcode.make(txt) img.save(dst)
A simple test :
mk_qr("hello world !", "text.jpg")
The generated QR code is as follows , Scan the code to see hello world !
word :
To generate a dynamic graph, you need to read the original gif
And generate a new gif
chart , That is, the function of reading and saving is required . Use opencv
Can easily read gif
, First installation opencv
library :
pip install opencv-python
Read gif
Each frame :
def parse_gif(path): frames = [] cap = cv2.VideoCapture(path) ret, image = cap.read() while ret: frames.append(image) ret, image = cap.read() cap.release() return frames
Use imageio
You can easily convert multiple frames of pictures into gif
chart , First installation imageio
:
pip install imageio
Save multi frame picture combination as gif
:
def save_gif(frames, dst, fps=60): imageio.mimsave(dst, frames, fps=fps)
Through the QR code, we can know which position pixel values are coding areas , What are the backgrounds . We need to set the coding area to 1, The background area is set to 0.
def load_qr(path): qr = cv2.imread(path) qr = cv2.cvtColor(qr, cv2.COLOR_BGR2GRAY) # Set the coding area to 1, The background area is set to 0 _, qr = cv2.threshold(qr, 240, 1, 1) qr = cv2.cvtColor(qr, cv2.COLOR_GRAY2BGR) return qr
We have a QR code ready , Get the mask shown below :
Get one ready gif chart
adopt parse_gif
Function gets every frame , Fuse each frame :
# Adjust picture brightness ,max_v Is the brightness value , The maximum is 1.0, The minimum is 0.0 def proc_frame(frame, max_v=1.0): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = gray / 255.0 scale = max_v / (np.max(gray) + 1e-8) frame = np.clip(frame * scale, 0 , 255).astype(np.uint8) return frame def mix(qr, frame): h, w = qr.shape[0:2] bg = np.ones((h, w, 3), np.uint8) * 255 frame = cv2.resize(frame, (w, h)) frame = proc_frame(frame) out = qr * frame + (1 - qr) * bg out = np.clip(out, 0, 255) out = cv2.cvtColor(out, cv2.COLOR_BGR2RGB).astype(np.uint8) return out
In order to prevent the QR code from being recognized because the frame is too white , You can call proc_fram
e Function to specify the maximum brightness value max_v
, If gif
Biased quantity , You can dim the overall brightness , Avoid that subsequent QR codes cannot be recognized .
It is recommended to use dark or brightly colored
gif
, Avoid using white or graygif
, Especially in the four corners , Avoid white .
Full code focus 【Python Learning from actual combat 】 official account , reply 2201
Get the complete code .
Welcome to follow me 【Python Learning from actual combat 】, Learn a little every day , Make a little progress every day .