DEV Community

Thanawat Srithongkul
Thanawat Srithongkul

Posted on

ตรวจจับวัตถุบนรูปด้วย OpenCV โดยใช้ Python

ตรวจจับวัตถุบนรูป หรือ Object Detection เป็นกระบวนการที่มีความสำคัญในการพัฒนาและประยุกต์ใช้งานในด้านการประมวลผลภาพ โดยสามารถนำ Object Detection ไปพัฒนาต่อในโปรเจกต์ IoT ที่ต้องการจับวัตถุในสถานการณ์ต่างๆ เช่น การตรวจจับการเคลื่อนไหวในบ้าน

ในบทความนี้เราจะสำรวจและเรียนรู้เกี่ยวกับการตรวจจับวัตถุด้วย OpenCV-Python ซึ่งเป็นไลบรารีที่มีความสามารถในการทำ Object Detection ได้อย่างมีประสิทธิภาพ

Haar Cascades
คลาสฟังก์ชัน Haar Cascade เป็นวิธีที่มีประสิทธิภาพสำหรับการตรวจจับวัตถุ วิธีนี้ถูกเสนอโดย Paul Viola และ Michael Jones ในบทความ Rapid Object Detection using a Boosted Cascade of Simple Features Haar Cascade เป็นวิธีการที่ใช้การเรียนรู้ของเครื่องโดยใช้ภาพบวกและภาพลบเพื่อฝึกคลาสฟังก์ชันตรวจจับวัตถุ

  • ขั้นตอนการทำ

ขั้นตอนที่ 1 นำเข้า libraries ที่ต้องใช้ทั้งหมด

pip install opencv-python
pip install matplotlib
import cv2
from matplotlib import pyplot as plt
Enter fullscreen mode Exit fullscreen mode

ขั้นตอนที่ 2 นำเข้ารูปภาพที่ต้องการตรวจจับ

ข้อมูลรูปภาพ: Download

# Opening image
img = cv2.imread("image.jpg")

# OpenCV opens images as BRG 
# but we want it as RGB and 
# we also need a grayscale 
# version
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Creates the environment 
# of the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()
Enter fullscreen mode Exit fullscreen mode

ผลที่ได้จาก code
Image description

ขั้นตอนที่ 3 ระบุข้อมูลด้วยการใช้ฟังก์ชัน detectMultiScale() ของ OpenCV ในการวิเคราะห์รูปภาพ

# Use minSize because for not 
# bothering with extra-small 
# dots that would look like STOP signs
stop_data = cv2.CascadeClassifier('stop_data.xml')
found = stop_data.detectMultiScale(img_gray, 
                                minSize =(20, 20))
# Don't do anything if there's 
# no sign
amount_found = len(found)


if amount_found != 0:

    # There may be more than one
    # sign in the image
    for (x, y, width, height) in found:

        # We draw a green rectangle around
        # every recognized sign
        cv2.rectangle(img_rgb, (x, y), 
                    (x + height, y + width), 
                    (0, 255, 0), 5)
Enter fullscreen mode Exit fullscreen mode

ขั้นตอนที่ 4 ตรวจสอบผลที่ได้

# Creates the environment of 
# the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()
Enter fullscreen mode Exit fullscreen mode

ผลที่ได้จาก code
Image description

Top comments (0)