Преобразование между строками и интергерами. Python - PullRequest
1 голос
/ 13 февраля 2020

Я строю сканер штрих-кода. Сканер работает как положено. Затем я решил изменить значение смещением ascii 5 для дополнительной защиты данных. Это также сработало, как и ожидалось. Для большей безопасности я добавлю sh пароль, который вводит пользователь. Мой оригинальный код до добавления пароля выглядит следующим образом ...

barcodeData = barcode.data.decode("ascii")

barcodeData = "".join(chr(ord(c) +5) for c in barcodeData

Затем я решил добавить пользовательский ввод в верхнюю строку

userkey = input()
key=float(userkey)

, а затем заменил

barcodeData = "".join(chr(ord(c) +5) for c in barcodeData

с

barcodeData = "".join(chr(ord(c) +'key') for c in barcodeData

это выдает ошибку

TypeError: неподдерживаемые типы операндов для +: 'int' и 'str'

I sh, чтобы система работала на всех входах и показала правильный вывод, только когда пользователь вводит число 5

, заранее спасибо

# import the necessary packages
from imutils.video import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
import imutils
import time
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", type=str, default="barcodes.csv",
    help="path to output CSV file containing barcodes")
args = vars(ap.parse_args())

#start video stream and allow warming of camera
print("While camera is warming up, please enter the numerical password.")
vs = VideoStream(usePiCamera=True).start()
time.sleep(2.0)
userkey=input()
key=str(userkey)


# open the output CSV file for writing and initialize the set of
# QR barcodes found thus far
csv = open(args["output"], "w")
found = set()

# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream and resize it to
    # have a maximum width of 600 pixels
    frame = vs.read()
    frame = imutils.resize(frame, width=600)

    # find the QR Codes in the frame and decode each of the barcodes
    barcodes = pyzbar.decode(frame)

    # loop over the detected barcodes
    for barcode in barcodes:
        # extract the bounding box location of the barcode and draw
        # the bounding box surrounding the barcode on the image
        (x, y, w, h) = barcode.rect
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3)


        # the barcode data is a bytes object so if we want to draw it
        # on our output image we need to convert it to a string first
        barcodeData = barcode.data.decode("ascii")


        #Chnage the decoded ascii string by a value of 5 charcters
        barcodeData = "".join(chr(ord(c) + 'key') for c in barcodeData)

        # draw the barcode data and barcode type on the image
        text = "{}".format(barcodeData)
        cv2.putText(frame, text, (x, y - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

        # if the barcode text is currently not in our CSV file, write
        # the timestamp + barcode to disk and update the set
        if barcodeData not in found:
            csv.write("{},{}\n".format(datetime.datetime.now(),
                barcodeData))
            csv.flush()
            found.add(barcodeData)

    # show the output frame
    cv2.imshow("QR Code Secret Message Scanner", frame)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

# close the output CSV file nad perform cleanup
csv.close()
cv2.destroyAllWindows()
vs.stop()

Ответы [ 2 ]

0 голосов
/ 13 февраля 2020

Измените эту строку (проблема в вашей строке, что ord возвращает int, а ключ имеет одинарные кавычки, что, как я полагаю, ошибка)

barcodeData = "".join(chr(ord(c) + 'key') for c in barcodeData)

на следующее:

barcodeData = "".join(chr(ord(c) + key) for c in barcodeData)

Пример :

key = 5 # your offset
barcode = 'AB1234VD'
barcode = "".join(chr(ord(c) + key) for c in barcode)
print(barcode) # 'FG6789[I'

PS не забудьте конвертировать key в вашем коде в int

0 голосов
/ 13 февраля 2020

key возвращается здесь не строка, а тип данных int, если вы хотите преобразовать его, вам придется набрать приведение к строке, выполнив:

key = str(userkey)

и аналогично строка для int будет:

key = int(userkey)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...