วันศุกร์ที่ 19 มิถุนายน พ.ศ. 2558

Image Processing on Ubutu 15.04 with Python & Opencv

      จากประสบการณ์ที่ติดตั้งระบบปฏิบัติการลินุกซ์หลายตระกูล และทดลองติดตั้งภาษาและไลบรารีสำหรับการประมวลผลภาพดิจิตอล พบว่า แต่ละภาษาและไลบรารีมีข้อจำกัดและมีความสามารถในการประมวลผลต่างกัน  ผู้เขียนเคยประมวลผลภาพดิจิตอลด้วยภาษา Python โดยใช้
ไลบรารีและแพคเกจต่าง ๆ เช่น Python Image Library, Scipy, Numpy และ Matplotlib ต่อมาได้ลอง
ประมวลผลด้วยภาษา Python และ Opencv สามารถใข้งานได้เป็นอย่างดี อีกทั้งสามารถใช้งาน
ร่วมกับ Scipy, Numpy และ Matplotlib ได้อย่างมีประสิทธิภาพ


        การติดติ้ง Opencv บนระบบปฏิบัติการลินุกซ์ Ubuntu ก็ทำได้ง่าย สามารถติดตั้งออนไลน์ได้เหมือนแพคเกจ หรือไลบรารีอื่น ๆ
         การติดตั้งใช้ Superuser หรือ root account ติดตั้งด้วยคำสั่ง

        apt-get install libopencv-dev python-opencv

        เพียงเท่านี้เราก็สามารถใช้งานภาษา Python ประมวลผลภาพร่วมกับแพคเกจ Opencv ได้แล้ว

        ตัวอย่างการเขียนโปรแกรม

1.  การเปิดและแสดงไฟล์ภาพ

ไฟล์ open.py

from cv2.cv import *
img = LoadImage("submarine.jpg")
NamedWindow("opencv")
ShowImage("opencv",img)
WaitKey(0)


สั่งรันด้วยคำสั่ง python open.py บน terminal  ได้ผลดังภาพข้างล่างนี้




2.  Canny Edge detection

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('submarine.jpg',0)
edges = cv2.Canny(img,100,200)

plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

plt.show()

สั่งรันได้ผลดังภาพข้างล่างนี้


3.  Threshold

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('submarine.jpg',0)
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)

thresh = ['img','thresh1','thresh2','thresh3','thresh4','thresh5']

for i in xrange(6):
    plt.subplot(2,3,i+1),plt.imshow(eval(thresh[i]),'gray')
    plt.title(thresh[i])

plt.show()


สั่งรันแล้วได้ผลดังภาพ


        จะเห็นได้ว่า Opencv สามารถใช้งานร่วมกับ Scipy, Numpy, Matplotlib ในการประมวลผลภาพ
ดิจิตอลด้วยภาษา Python ได้เป็นอย่างดี เพื่อเปรียบเทียบกับภาษา Java หรือภาษา  C, C++ 
ภาษา Python จะเขียนด้วยไวยากรณืที่สั้นกว่า







ไม่มีความคิดเห็น:

แสดงความคิดเห็น