tinkering好きの素人

ものづくりの記録

pythonによるQRコード読み取りの文字化けを直した

webカメラやPC内蔵のカメラで日本語のQRを読み取る際、しょっちゅう文字化けしたので直した。
エンコードがshift-JISと思われたりutf-8と思われたりしてしまうのが原因だったよう。

from pyzbar.pyzbar import decode 
import cv2
   
capture = cv2.VideoCapture(0)#引数はPC内蔵なら0,webカメラなら1以降のことが多い
cv2.waitKey(10)
    
while(True):
        ret, frame = capture.read()
        gray_scale = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        image = edit_contrast(gray_scale, 5)
        codes = decode(image)
        cv2.waitKey(10)
        if len(codes) > 0:
            try:
                receive_text = codes[0].data.decode("utf-8").encode("shift-jis").decode("utf-8")
            except:
                receive_text = codes[0].data.decode("utf-8")