나의 여행과 일상 일기장

(2) 캡스톤디자인 2강_라즈베리파이 환경에서 LAMP설치 본문

일상일기

(2) 캡스톤디자인 2강_라즈베리파이 환경에서 LAMP설치

똥글똥글 2022. 4. 24. 12:55
반응형

1. 리눅스 환경에 파이썬 설치 후 컴퓨터비전 기술 적용

https://emaru.tistory.com/15 블로그 참고

 

 1) 컴퓨터비전 예제 코드

#!/usr/bin/etc python

import cv2
import numpy as np
import pytesseract
from  PIL import Image

class Recognition:
     def ExtractNumber(self):
          Number='testimg3.jpg' 
          img=cv2.imread(Number,cv2.IMREAD_COLOR)
          copy_img=img.copy()
          img2=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
          cv2.imwrite('gray.jpg',img2)
          blur = cv2.GaussianBlur(img2,(3,3),0)
          cv2.imwrite('blur.jpg',blur)
          canny=cv2.Canny(blur,100,200)
          cv2.imwrite('canny.jpg',canny)
          cnts,contours,hierarchy  = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

          box1=[]
          f_count=0
          select=0
          plate_width=0
          
          for i in range(len(contours)):
               cnt=contours[i]          
               area = cv2.contourArea(cnt)
               x,y,w,h = cv2.boundingRect(cnt)
               rect_area=w*h  #area size
               aspect_ratio = float(w)/h # ratio = width/height
                  
               if  (aspect_ratio>=0.2)and(aspect_ratio<=1.0)and(rect_area>=100)and(rect_area<=700): 
                    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1)
                    box1.append(cv2.boundingRect(cnt))
         
          for i in range(len(box1)): ##Buble Sort on python
               for j in range(len(box1)-(i+1)):
                    if box1[j][0]>box1[j+1][0]:
                         temp=box1[j]
                         box1[j]=box1[j+1]
                         box1[j+1]=temp
                         
         #to find number plate measureing length between rectangles
          for m in range(len(box1)):
               count=0
               for n in range(m+1,(len(box1)-1)):
                    delta_x=abs(box1[n+1][0]-box1[m][0])
                    if delta_x > 150:
                         break
                    delta_y =abs(box1[n+1][1]-box1[m][1])
                    if delta_x ==0:
                         delta_x=1
                    if delta_y ==0:
                         delta_y=1           
                    gradient =float(delta_y) /float(delta_x)
                    if gradient<0.25:
                        count=count+1
               #measure number plate size         
               if count > f_count:
                    select = m
                    f_count = count;
                    plate_width=delta_x
          cv2.imwrite('snake.jpg',img)
          
          
          number_plate=copy_img[box1[select][1]-10:box1[select][3]+box1[select][1]+20,box1[select][0]-10:140+box1[select][0]] 
          resize_plate=cv2.resize(number_plate,None,fx=1.8,fy=1.8,interpolation=cv2.INTER_CUBIC+cv2.INTER_LINEAR) 
          plate_gray=cv2.cvtColor(resize_plate,cv2.COLOR_BGR2GRAY)
          ret,th_plate = cv2.threshold(plate_gray,150,255,cv2.THRESH_BINARY)
          
          cv2.imwrite('plate_th.jpg',th_plate)
          kernel = np.ones((3,3),np.uint8)
          er_plate = cv2.erode(th_plate,kernel,iterations=1)
          er_invplate = er_plate
          cv2.imwrite('er_plate.jpg',er_invplate)
          result = pytesseract.image_to_string(Image.open('er_plate.jpg'), lang='kor')
          return(result.replace(" ",""))

    
recogtest=Recognition()
result=recogtest.ExtractNumber()
print(result)

- 결과

//간단하게 이미지를 불러와서 영상처리를 한 후 터미널 콘솔창에 추출된 텍스트가 출력되는 것까지 완료

//원하는 글자는 아니었지만 어느정도 간단한 코드로 출력은 된다.

2. 원격 시스템 구축

https://m.blog.naver.com/tipsware/220991540922 블로그 참고

 

외부 출력 장치가 없어도 되는 장점이 있지만 처리속도가 절반으로 느려지기 때문에 모니터를 가지고 다니는 것이 좋다.

PC에서 ‘원격데스크톱’ 클릭

파이 IP: xxx.xxx.xxx.xxx

원격 데스크톱에서 라즈베리파이 종료: sudo shutdown -h now

 

3. 라즈베리파이에 LAMP(Linux, Apache2, MariaDB, Python)을 설치하여 웹서버로 구현

https://bugwhale.tistory.com/entry/raspberrypi-raspbian-apm-install 블로그 참고

 

라즈베리파이에서 데이터베이스 설치할 때 라즈베리파이 업데이트로 인해 mySQL은 설치할 수 없다. 대신 MariaDB 로 대체되었다.

라즈베리파이 서버가 활성화 되어있다면 pc로 192.168.0.52/phpmyadmin으로 접속 후 ID, Password 입력하면 어디서든 접속가능

 

4. 파이썬 프로그래밍으로 데이터베이스 제어

http://pythonstudy.xyz/python/article/202-MySQL-%EC%BF%BC%EB%A6%AC 블로그 참고

 

https://godoftyping.wordpress.com/2017/05/27/python-mysql/ 블로그 참고

 

Imgprocess.py 코드에서 데이터베이스 입력에 대한 코드 삽입

 1) imgprocess.py

import pymysql

conn = pymysql.connect(host='localhost',
                       user='phpmyadmin',
                       password='1234'
                       db='testDB',
                       charset='utf8')

curs=conn.cursor()
sql = "insert into Data(id,time, locate, image, text, same,imsame, realtext)
    VALUES(%s, %s, %s, %s, %s, %s, %s, %s)"

curs.execute(sql, (3, '2020-03-17', 'B2', Number, result, 'o', '-','-'))

conn.commit()

conn.close()

//DB에 연결하고 SQL insert명령을 이용하여 8개의 요소를 넣어줌

//리눅스 환경에서 파이썬으로 데이터베이스에 값 입력하기(기본 틀)

반응형