I was building a Processing Images API, which is composed by 3 steps, remove the image background, blur the QRCode if found it and change the background to White.
At first worked using some standard images with QRCode.
But in the meantime, some images began to blur other areas which doesn't have QRCode.
If someone know how to do it properly, i'll be grateful.
My code (func) :
def blur_qrcode(path, image : Mat):
is_qrcode = pyzbar.decode(image=image, symbols=[pyzbar.ZBarSymbol.QRCODE])
# # if there is a QR code
if is_qrcode:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 196, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) > 100: # Adjust if needed
x, y, w, h = cv2.boundingRect(contour)
qrcode_area = image[y:y+h, x:x+w]
qrcode_gray = cv2.cvtColor(qrcode_area, cv2.COLOR_BGR2GRAY)
_, qrcode_thresh = cv2.threshold(qrcode_gray, 196, 255, cv2.THRESH_BINARY)
qrcode_contours, _ = cv2.findContours(qrcode_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
qrcode_mask = np.zeros(qrcode_gray.shape, dtype=np.uint8)
for qrcode_contour in qrcode_contours:
if cv2.contourArea(qrcode_contour) > 10: # Adjust if needed
cv2.drawContours(qrcode_mask, [qrcode_contour], -1, 255, -1)
qrcode_blurred = cv2.GaussianBlur(qrcode_area, (25, 25), 0)
image[y:y+h, x:x+w] = qrcode_blurred
file_name = secrets.token_hex(8) + '_blurred.png'
full_path = os.path.join(path, file_name)
if cv2.imwrite(full_path, image):
return full_path
else:
return ''
else:
return 'no_qrcode'
Using opencv pyzbar
Expected to Only blur the QRCode.