티스토리 뷰

728x90
반응형

>>참고 사이트

https://shiinachianti.tistory.com/7

 

Python :: 네이버 Book API로 책 데이터 가져오기

Edit Python :: 네이버 Book API로 책 데이터 가져오기 프로젝트 파우스트를 만들면서 네이버 북 API를 사용했는데, 꽤 괜찮았던 관계로 여기에 한번 정리해보려고 합니다. 네이버 책 API 로그인 및 등록

shiinachianti.tistory.com

https://rfriend.tistory.com/250

 

[Python pandas] text, csv 파일 불러오기 : pd.read_csv()

Python 을 가지고 분석에 활용한다고 했을 때 데이터 전처리에 NumPy와 pandas library를 많이 사용합니다. 특히, 행과 열로 구성이 되어있는 DataFrame type 데이터를 입력, 처리, 조작할 때 pandas 가 매우 강

rfriend.tistory.com

 

1. 환경

실시간으로 라즈베리파이 카메라가 바코드를 인식하고, csv 파일에 ( 날짜+시간  , isbn 코드 )로 저장되게 되어있다.

이전 게시글 >> https://ing-min.tistory.com/56

 

라즈베리파이_OpenCV_QR 바코드 인식

<라즈베리파이 카메라를 활용하여 QR,바코드를 인식해보자 ! > >>> 참고 사이트 (두개의 과정은 같지만 아래거는 영어고 더 자세하다.) https://blog.naver.com/PostView.nhn?blogId=zzang9ha&logNo=221660190400..

ing-min.tistory.com

>> 비디오 스트림 바코드 csv 저장 파일 .py

from imutils.video import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
import imutils
import time
import cv2
from playsound import playsound
import numpy as np

def autocrop(image, threshold=0):
    """Crops any edges below or equal to threshold
    Crops blank image to 1x1.
    Returns cropped image.
    """
    if len(image.shape) == 3:
        flatImage = np.max(image, 2)
    else:
        flatImage = image
    assert len(flatImage.shape) == 2

    rows = np.where(np.max(flatImage, 0) > threshold)[0]
    if rows.size:
        cols = np.where(np.max(flatImage, 1) > threshold)[0]
        image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]
    else:
        image = image[:1, :1]

    return image


#argument parser
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())


#from there, initialize our video stream and open our CSV file
print("[INFO] starting video stream...")

#camera setting
resolution = (1296, 976)

vs = VideoStream(usePiCamera=True,resolution=resolution,
                    framerate=24).start()


time.sleep(2.0)

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

#bool _
isComplete = False

#carturing + processing frame
#loop over the frames from video strea
while True:
    #frame
    frame = vs.read()
    frame = imutils.resize(frame, width = 1200)

    #crop def
    crop = autocrop(frame,50)

    #barcode in frame and decode
    # barcodes = pyzbar.decode(frame)
    barcodes = pyzbar.decode(crop)


    #loop over the detected barcodes 
    for barcode in barcodes:
        #draw red box
        (x,y,w,h) = barcode.rect
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)

        #bype to text
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type

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

        #found = our CSV file
        if barcodeData not in found:
            csv.write("{},{}\n".format(datetime.datetime.now(),barcodeData))
            csv.flush()
            found.add(barcodeData)
            print("인식 성공 :",barcodeData)
            playsound("barcode_beep.mp3")
        else :
            # csv.write("{},{}\n".format(datetime.datetime.now(),barcodeData))
            # csv.flush()
            #print type , data to the terminal
            print("이미 인식된 코드 [INFO] Found {} barcode: {}".format(barcodeData,barcodeType))
            playsound("barcode_beep.mp3")
            isComplete= True
        break

    #close
    if isComplete:
        print("recognition complete")
        break
            
            

    #show output image
    cv2.imshow("Barcode Scanner",frame)
    key = cv2.waitKey(1) & 0xFF

    #q press loop break
    if key == ord("q"):
        break

#close the output CSV file do a bit of clean up
print("[INFO] cleaning up...")
csv.close()
cv2.destroyAllWindows()
vs.stop()

2. 목표

네이버 api를 활용하여 csv 파일에 저장된 isbn 코드를 불러와서 책 정보를 받아오고 싶다.

참고 : https://kuklife.tistory.com/87

>> naver book api 책 제목 가격 받아오기. py

CLIENT_ID = '00'
CLIENT_SECRET = '00'


def search_book(query):

    from urllib.request import Request, urlopen

    from urllib.parse import urlencode, quote

    import json



    # request = Request('https://openapi.naver.com/v1/search/book?query='+quote(query))
    #isbn
    request = Request('https://openapi.naver.com/v1/search/book_adv?d_isbn='+quote(query))

    request.add_header('X-Naver-Client-Id', CLIENT_ID)

    request.add_header('X-Naver-Client-Secret', CLIENT_SECRET)



    response = urlopen(request).read().decode('utf-8')

    search_result = json.loads(response)

    return search_result




if __name__ == "__main__":

    books = search_book('9791196566821')['items']
    if(books == None):
        print("fail")
        exit()
    
    #print
    for book in books:

        # print(book)
        print("title: " + book['title'])
        print("price: "+book["price"]+"won")

 

>> 이 파일에서 isbn 값을 csv에서 받아오게 한다

참고 : https://datalibrary.tistory.com/48

import csv

#naver api
CLIENT_ID = '000'
CLIENT_SECRET = '000'


#request
def search_book(query):

    from urllib.request import Request, urlopen

    from urllib.parse import urlencode, quote

    import json



    # request = Request('https://openapi.naver.com/v1/search/book?query='+quote(query))
    #isbn
    request = Request('https://openapi.naver.com/v1/search/book_adv?d_isbn='+quote(query))

    request.add_header('X-Naver-Client-Id', CLIENT_ID)

    request.add_header('X-Naver-Client-Secret', CLIENT_SECRET)



    response = urlopen(request).read().decode('utf-8')

    search_result = json.loads(response)

    return search_result






if __name__ == "__main__":
    #csv first line only
    f = open('barcodes.csv', 'r', encoding='utf-8')
    rdr = csv.reader(f)
    for line in rdr:
        #search
        print(line[1])
        books = search_book(line[1])['items']

        #erro
        if(books == None):
            print("fail")
            exit()
        
        #print
        for book in books:

            # print(book)
            print("title: " + book['title'])
            print("price: "+book["price"]+"won")
    f.close()

 

라즈베리파이 카메라로 바코드를 인식하고 isbn값을 csv 파일에 저장 -> isbn 값을 불러와 naver api에 보내고

책 정보 (제목, 가격)을 받아왔다.

 

3. 다음 과제

> 버튼을 연결하여 버튼을 누르면 동작하게

> LCD 패널에 연결하여 받아온 값을 표시한다.

728x90
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함
반응형