Created
August 24, 2022 07:18
-
-
Save yushulx/552a2722bfff46605a9e060f766d7d0b to your computer and use it in GitHub Desktop.
OpenCV Python: rotate and draw a barcode QR code image over a background image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pip install python-barcode pylibdmtx opencv-python | |
from PIL import Image | |
from pylibdmtx.pylibdmtx import encode, decode | |
import cv2 | |
import numpy | |
from barcode import UPCA | |
from barcode.writer import ImageWriter | |
number = 10000000000 | |
def resize_image(src, scale_factor): | |
width = int(src.shape[1] * scale_factor) | |
height = int(src.shape[0] * scale_factor) | |
dim = (width, height) | |
return cv2.resize(src, dim) | |
# https://stackoverflow.com/questions/9041681/opencv-python-rotate-image-by-x-degrees-around-specific-point | |
def rotate_image(image, angle): | |
image_center = tuple(numpy.array(image.shape[1::-1]) / 2) | |
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 0.5) | |
result = cv2.warpAffine( | |
image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) | |
return result | |
for i in range(5): | |
encoded = encode(str(i).encode('utf8')) | |
img = Image.frombytes( | |
'RGB', (encoded.width, encoded.height), encoded.pixels) | |
src = numpy.array(img) | |
# resize image | |
scale_factor = 1.5 | |
src = resize_image(src, scale_factor) | |
# load image | |
dest = cv2.imread(str(i % 10) + '.jpg') | |
# draw DataMatrix code | |
left = 10 | |
top = 40 | |
offset = 125 | |
dest[top:top + src.shape[0], dest.shape[1] - | |
offset: dest.shape[1] - offset + src.shape[1]] = src | |
# draw UPCA | |
print(number) | |
number_to_str = str(number) | |
upca_code = UPCA(str(number_to_str), writer=ImageWriter()) | |
upca_code.save(number_to_str) | |
src = cv2.imread(number_to_str + '.png') | |
# https://stackoverflow.com/questions/14063070/overlay-a-smaller-image-on-a-larger-image-python-opencv | |
src = cv2.cvtColor(src, cv2.COLOR_BGR2RGBA) | |
# src = cv2.rotate(src, cv2.ROTATE_90_CLOCKWISE) | |
src = rotate_image(src, 70) | |
# resize upca image | |
scale_factor = 0.9 | |
src = resize_image(src, scale_factor) | |
left = 2 | |
top = 35 | |
dest = cv2.cvtColor(dest, cv2.COLOR_RGB2RGBA) | |
# dest[top:top + src.shape[0], left: left + src.shape[1]] = src | |
y1, y2 = top, top + src.shape[0] | |
x1, x2 = left, left + src.shape[1] | |
alpha_s = src[:, :, 3] / 255.0 | |
alpha_l = 1.0 - alpha_s | |
for c in range(0, 3): | |
dest[y1:y2, x1:x2, c] = (alpha_s * src[:, :, c] + | |
alpha_l * dest[y1:y2, x1:x2, c]) | |
cv2.imshow(str(i), dest) | |
cv2.imwrite('{0}x{1}_{2}.png'.format( | |
dest.shape[1], dest.shape[0], i), dest) | |
number += 1 | |
cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment