Program to adjust the QR code that is scaled horizontally and vertically

Tweet


The program that adjusts the distorted QR code image into a correct shape. This program can be used when the QR code is vertically scaled and horizontally scaled. Please use this program if you want to adjust the QR code that is distorted as such.

Make a new Python file in Google Colab, and paste the source code below.

Suppose that you want to adjust input.png file. If you run this program, you can uploade this file. After that, the resultant output.png file is downloaded.


input.png


output.png


from google.colab import files
import os
import numpy as np
import cv2
def main():
  if os.path.exists('input.png'):
     os.remove('input.png')
  files.upload()
  input=cv2.imread('input.png',cv2.IMREAD_GRAYSCALE)
  _,input=cv2.threshold(input,128,255,cv2.THRESH_BINARY)
  oldrows,oldcols=input.shape
  threshold=(oldrows+oldcols)*0.01
  posx=[0]
  for x in range(1,oldcols):
    n=0
    for y in range(0,oldrows):
      if input[y,x]!=input[y,x-1]:
        n+=1
    if n>threshold:
      posx.append(x)
  posy=[0]
  for y in range(1,oldrows):
    n=0
    for x in range(0,oldcols):
      if input[y,x]!=input[y-1,x]:
        n+=1
    if n>threshold:
      posy.append(y)
  newrows=len(posy)*8
  newcols=len(posx)*8
  output=np.zeros((newrows,newcols),dtype=np.uint8)
  for yy in range(0,len(posy)):
    for xx in range(0,len(posx)):
      yy1=posy[yy]
      if yy<len(posy)-1:
        yy2=posy[yy+1]
      else:
        yy2=oldrows
      xx1=posx[xx]
      if xx<len(posx)-1:
        xx2=posy[xx+1]
      else:
        xx2=oldcols
      val=input[(yy1+yy2-1)//2,(xx1+xx2-1)//2]
      for y in range(yy*8,(yy+1)*8):
        for x in range(xx*8,(xx+1)*8):
          output[y,x]=val
  cv2.imwrite('output.png',output)
  files.download('output.png')
if __name__=='__main__':
  main()


Back