影像處理

OpenCV

圖片處理



                # 需用本機端py環境開啟,不可用ipynb
                import cv2
                import numpy as np
                # 讀取圖片
                img = cv2.imread('pic.jpg')
                img = cv2.resize(img, (100, 100)) # 調整圖片大小為 100x100
                img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5) # 調整圖片xy大小為原來的0.5倍
                cv2.imshow('img', img) # 開視窗顯示圖片
                cv2.waitKey(1000) # 等待1000ms後關閉,若0則無限時

                # 圖片處理
                # 灰諧 (img, cv2.COLOR_BGR2GRAY)
                gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

                # 高斯模糊 (img, kernel, std),kernel, std調大會更模糊
                blur = cv2.GaussianBlur(img, (3,3), 0)

                # 取得邊緣 (最低門檻, 最高門檻),降低門檻範圍可以提升找到圖片邊緣數量
                canny = cv2.Canny(img, 150, 200)

                # 膨脹 (img, kernel, iterations) iterations要膨幾次
                kernel = np.ones((3,3), np.unit8) # 提升大小可以增加膨脹的程度
                dilate = cv2.dilate(canny, kernel, iterations = 1)

                # 輕實 (img, kernel, iterations) iterations要輕實幾次
                kernel2 = np.ones((3,3), np.unit8) # 提升大小可以增加輕實的程度
                erode = cv2.erode(dilate, kernel2, iterations = 1)

            

影片處理



                import cv2
                # 讀取影片
                video = cv2.VideoCapture('video.mp4') # 讀取影片檔
                cap = cv2.VideoCapture(1) # 使用影像輸入鏡頭編號#1

                """
                cap.read() Returns:
                * ret: 取得下一楨有沒有成功, Bool
                * frame: 若ret為True,則回傳下一楨的圖片
                """
                ret, frame = cap.read()
                if ret:
                    cv2.imshow('video', frame) # 開視窗顯示圖片

                # 顯示影片第1楨
                cv2.waitKey(0)

                # 影片連續播放
                while True:
                    ret, frame = cap.read()
                    if ret:
                        cv2.imshow('video', frame)
                    else:
                        break
                    if cv2.waitKey(1) == ord('q'): # 在播放影片時按「q」會退出播放
                        break
            

輪廓識別與標示