1. 程式人生 > >python for OpenCV影象處理之模板匹配以及分水嶺演算法

python for OpenCV影象處理之模板匹配以及分水嶺演算法

首先看些效果如下:
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述

具體程式碼如下:

if __name__ == '__main__':
    from muban import Ui_Form
else:
    from muban.muban import Ui_Form
from PyQt5.QtWidgets import QWidget, QFileDialog
from PyQt5.QtCore import QFileInfo
import cv2
import numpy as np
from matplotlib.patches import Rectangle

class mubanWindows
(QWidget):
"""docstring for mubanWindows""" # def __init__(self): # super(mubanWindows, self).__init__() def init_fun(self): self.window = Ui_Form() self.window.setupUi(self) self.curFile = "匹配變換" self.window.mb_openmb_btn.clicked.connect(self.mb_openmb_btn_fun) self.window.mb_opensrc_btn.clicked.connect(self.mb_opensrc_btn_fun) self.window.mb_startpp_btn.clicked.connect(self.mb_startpp_btn_fun) self.window.mb_ddxpp_btn.clicked.connect(self.mb_ddxpp_btn_fun) self.window.H_lines_open_btn.clicked.connect(self.H_lines_open_btn_fun) self.window.H_yuan_open_btn.clicked.connect(self.H_yuan_open_btn_fun) self.window.H_lines_bh_btn.clicked.connect(self.H_lines_bh_btn_fun) self.window.H_yuan_bh_btn.clicked.connect(self.H_yuan_bh_btn_fun) def
userFriendlyCurrentFile(self):
return self.strippedName(self.curFile) def strippedName(self, fullFileName): return QFileInfo(fullFileName).fileName() def H_yuan_bh_btn_fun(self): img = self.h_yuan_img.copy() img = cv2.medianBlur(img, 5) cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) method = eval("cv2.HOUGH_"
+ self.window.H_yuan_method_comboBox.currentText()) dp = self.window.H_yuan_dp_spinBox.value() circle = self.window.H_yuan_circles_spinBox.value() param1 = self.window.H_yuan_param1_spinBox.value() param2 = self.window.H_yuan_param2_spinBox.value() minRad = self.window.H_yuan_min_spinBox.value() maxRad = self.window.H_yuan_max_spinBox.value() circles = cv2.HoughCircles(img, method, dp, circle, param1=param1, param2=param2, minRadius=minRad, maxRadius=maxRad) circles = np.uint16(np.around(circles)) for i in circles[0, :]: cv2.circle(cimg, (i[0], i[1]), i[2], (0,255,0), 2) cv2.circle(cimg, (i[0], i[1]), 2, (0,0,255), 3) self.window.hough_figaxes.clear() self.window.hough_figaxes.imshow(cimg) self.window.hough_figaxes.autoscale_view() self.window.hough_figure.canvas.draw() def H_yuan_open_btn_fun(self): fileName = self.open_image_file() if fileName: # self.hough_figure, self.hough_figaxes = plt.subplots() self.h_yuan_img = cv2.imread(fileName, 0) # b, g, r = cv2.split(self.h_yuan_img) imgret = self.h_yuan_img self.window.hough_figaxes.clear() self.window.hough_figaxes.imshow(imgret, cmap='gray') self.window.hough_figaxes.autoscale_view() self.window.hough_figure.canvas.draw() def H_lines_bh_btn_fun(self): img = self.h_lines_img.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) p = self.window.H_lines_p_spinBox.value() jingdu = self.window.H_lines_jd_doubleSpinBox.value() yuzhi = self.window.H_lines_yuzhi_spinBox.value() lines = cv2.HoughLines(edges, p, np.pi/int(jingdu), yuzhi) for rho,theta in lines[0]: a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img, (x1,y1), (x2,y2), (0,0,255), 2) b, g, r = cv2.split(img) imgret = cv2.merge([r,g,b]) self.window.hough_figaxes.clear() self.window.hough_figaxes.imshow(imgret) self.window.hough_figaxes.autoscale_view() self.window.hough_figure.canvas.draw() def H_lines_open_btn_fun(self): fileName = self.open_image_file() if fileName: # self.hough_figure, self.hough_figaxes = plt.subplots() self.h_lines_img = cv2.imread(fileName) b, g, r = cv2.split(self.h_lines_img) imgret = cv2.merge([r,g,b]) self.window.hough_figaxes.clear() self.window.hough_figaxes.imshow(imgret) self.window.hough_figaxes.autoscale_view() self.window.hough_figure.canvas.draw() def mb_ddxpp_btn_fun(self): # method_str = "cv2." + self.window.mb_ff_comboBox.currentText() # method = eval(method_str) h = self.mu_img.shape[0] w = self.mu_img.shape[1] if hasattr(self, "mu_img") and hasattr(self, "src_img"): img = self.src_img.copy() res = cv2.matchTemplate(img, self.mu_img, cv2.TM_CCOEFF_NORMED) threshold = self.window.mb_yuzhi_doubleSpinBox.value() loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(img, pt, (pt[0]+w, pt[1]+h), (0,0,255), 2) self.window.mb_figaxes2.clear() self.window.mb_figaxes2.imshow(res, cmap='gray') self.window.mb_figaxes2.autoscale_view() self.window.mb_figure2.canvas.draw() b, g, r = cv2.split(img) imgret = cv2.merge([r,g,b]) self.window.mb_figaxes1.clear() self.window.mb_figaxes1.imshow(imgret) self.window.mb_figaxes1.autoscale_view() self.window.mb_figure1.canvas.draw() def mb_startpp_btn_fun(self): method_str = "cv2." + self.window.mb_ff_comboBox.currentText() method = eval(method_str) h = self.mu_img.shape[0] w = self.mu_img.shape[1] if hasattr(self, "mu_img") and hasattr(self, "src_img"): img = self.src_img.copy() res = cv2.matchTemplate(img, self.mu_img, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0]+w, top_left[1]+h) cv2.rectangle(img, top_left, bottom_right, (0,0,255) , 2) self.window.mb_figaxes2.clear() self.window.mb_figaxes2.imshow(res, cmap='gray') self.window.mb_figaxes2.autoscale_view() self.window.mb_figure2.canvas.draw() b, g, r = cv2.split(img) imgret = cv2.merge([r,g,b]) self.window.mb_figaxes1.clear() self.window.mb_figaxes1.imshow(imgret) self.window.mb_figaxes1.autoscale_view() self.window.mb_figure1.canvas.draw() def mb_openmb_btn_fun(self): fileName = self.open_image_file() if fileName: self.mu_img = cv2.imread(fileName) b, g, r = cv2.split(self.mu_img) imgret = cv2.merge([r,g,b]) self.window.mb_figaxes.clear() self.window.mb_figaxes.imshow(imgret) self.window.mb_figaxes.autoscale_view() self.window.mb_figure.canvas.draw() def mb_opensrc_btn_fun(self): fileName = self.open_image_file() if fileName: self.src_img = cv2.imread(fileName) b, g, r = cv2.split(self.src_img) imgret = cv2.merge([r,g,b]) self.window.mb_figaxes1.clear() self.window.mb_figaxes1.imshow(imgret) self.window.mb_figaxes1.autoscale_view() self.window.mb_figure1.canvas.draw() def open_image_file(self): '''開啟一個影象檔案''' fileName, filetype= QFileDialog.getOpenFileName(self.window.widget, "open file", '.', "jpg Files (*.jpg);;png Files (*.png);;All Files (*)") return fileName if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication , QMainWindow app = QApplication(sys.argv) mainW = QMainWindow() mainW.resize(1064, 667) ui = mubanWindows(mainW) ui.init_fun() mainW.show() sys.exit(app.exec_())
if __name__ == '__main__':
    from windows_ui import Ui_Form
else:
    from windows.grabcut.windows_ui import Ui_Form
from PyQt5.QtWidgets import QWidget, QFileDialog
from PyQt5.QtCore import QFileInfo
import cv2
import numpy as np
from matplotlib.patches import Rectangle

class grabcutWindows(QWidget):
    """docstring for mubanWindow"""
    # def __init__(self):
    #     super(mubanWindow, self).__init__()
    def init_fun(self):
        self.window = Ui_Form()
        self.window.setupUi(self)
        self.curFile = "GrabCut"

        self.window.fens_load_src_btn.clicked.connect(self.fens_load_src_btn_fun)
        self.window.fens_OK_btn.clicked.connect(self.fens_OK_btn_fun)

        self.window.tiqu_open_Src_btn.clicked.connect(self.fens_load_src_btn_fun)

        self.window.fs_figure1.canvas.mpl_connect("button_press_event", self.fs_figure1_on_press)
        self.window.fs_figure1.canvas.mpl_connect("button_release_event", self.fs_figure1_on_release)

        self.window.tiqu_tiqu_btn.clicked.connect(self.tiqu_tiqu_btn_fun)
        self.window.tiqu_xiugai_btn.clicked.connect(self.tiqu_xiugai_btn_fun)

    def fs_figure1_on_press(self, event):
        self.x0 = int(event.xdata)
        self.y0 = int(event.ydata)
        self.window.tiqu_x0_spinBox.setValue(self.x0)
        self.window.tiqu_y0_spinBox.setValue(self.y0)
        while len(self.window.fs_figaxes1.patches)>0:
                del self.window.fs_figaxes1.patches[0]
        self.fs_figure1_rect = Rectangle((0,0), 0, 0, linestyle='solid', fill=False, edgecolor='red')
        self.window.fs_figaxes1.add_patch(self.fs_figure1_rect)

    def fs_figure1_on_release(self, event):
        self.x1 = int(event.xdata)
        self.y1 = int(event.ydata)
        self.window.tiqu_x1_spinBox.setValue(self.x1)
        self.window.tiqu_y1_spinBox.setValue(self.y1)
        self.fs_figure1_rect.set_width(self.x1 - self.x0 + 1)
        self.fs_figure1_rect.set_height(self.y1 - self.y0 + 1)
        self.fs_figure1_rect.set_xy((self.x0, self.y0))
        self.window.fs_figure1.canvas.draw()

    def userFriendlyCurrentFile(self):
        return self.strippedName(self.curFile)

    def strippedName(self, fullFileName):
        return QFileInfo(fullFileName).fileName()

    def tiqu_xiugai_btn_fun(self):
        tiqu_img = self.img.copy()
        mask = np.zeros(self.tiqu_img.shape[:2], np.uint8)
        bgdModel = np.zeros((1,65), np.float64)
        fgdModel = np.zeros((1,65), np.float64)
        x0 = self.window.tiqu_x0_spinBox.value()
        y0 = self.window.tiqu_y0_spinBox.value()
        w = self.window.tiqu_x1_spinBox.value() - x0 + 1
        h = self.window.tiqu_y1_spinBox.value() - y0 + 1
        rect = self.frist_rect#(x0, y0, w, h)
        # 函式的返回值是更新的mask,bgdModel,fgdModel
        diecount = self.window.tiqu_diedai_spinBox.value()
        cv2.grabCut(tiqu_img, mask, rect, bgdModel, fgdModel, diecount, cv2.GC_INIT_WITH_RECT)
        # newmask = cv2.imread('./image/newmessi5.jpg', 0)
        # mask[newmask == 0] = 0
        # mask[newmask == 255] = 1
        if self.window.radioButton.isChecked():# 這裡的這個方法需要改正,背景和前景一起標記出來才可以
            print("前景")
            mask[x0:w,y0:h] = 0
        else:
            mask[x0:w,y0:h] = 1
        mask, bgdModel, fgdModel = cv2.grabCut(tiqu_img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)

        mask = np.where((mask==2)|(mask==0), 0, 1).astype('uint8')
        tiqu_img = tiqu_img*mask[:,:,np.newaxis]
        b, g, r = cv2.split(tiqu_img)
        imgret = cv2.merge([r,g,b])
        self.window.fs_figaxes2.clear()
        self.window.fs_figaxes2.imshow(imgret)
        self.window.fs_figaxes2.autoscale_view()
        self.window.fs_figure2.canvas.draw()

    def tiqu_tiqu_btn_fun(self):
        self.tiqu_img = self.img.copy()
        self.mask = np.zeros(self.tiqu_img.shape[:2], np.uint8)
        self.bgdModel = np.zeros((1,65), np.float64)
        self.fgdModel = np.zeros((1,65), np.float64)
        x0 = self.window.tiqu_x0_spinBox.value()
        y0 = self.window.tiqu_y0_spinBox.value()
        w = self.window.tiqu_x1_spinBox.value() - x0 + 1
        h = self.window.tiqu_y1_spinBox.value() - y0 + 1
        self.frist_rect = (x0, y0, w, h)
        # 函式的返回值是更新的mask,bgdModel,fgdModel
        diecount = self.window.tiqu_diedai_spinBox.value()
        cv2.grabCut(self.tiqu_img, self.mask, self.frist_rect, self.bgdModel, self.fgdModel, diecount, cv2.GC_INIT_WITH_RECT)

        self.mask = np.where((self.mask==2)|(self.mask==0), 0, 1).astype('uint8')
        self.tiqu_img = self.tiqu_img*self.mask[:,:,np.newaxis]
        b, g, r = cv2.split(self.tiqu_img)
        imgret = cv2.merge([r,g,b])
        self.window.fs_figaxes2.clear()
        self.window.fs_figaxes2.imshow(imgret)
        self.window.fs_figaxes2.autoscale_view()
        self.window.fs_figure2.canvas.draw()

    def fens_OK_btn_fun(self):
        if hasattr(self, 'img'):
            img = self.img.copy()
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
            # noise removal 
            kernel = np.ones((3,3), np.uint8)
            opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
            # sure background area
            sure_bg = cv2.dilate(opening, kernel, iterations=3)
            dist = eval("cv2." + self.window.fens_dist_comboBox.currentText())
            diedai = self.window.fens_san_spinBox.value()
            dist_transform = cv2.distanceTransform(opening,dist,diedai)
            yuzhi = self.window.fens_yuzhi_doubleSpinBox.value()
            ret, sure_fg = cv2.threshold(dist_transform, yuzhi*dist_transform.max(), 255,0)
            # Finding unknown region
            sure_fg = np.uint8(sure_fg)
            unknown = cv2.subtract(sure_bg, sure_fg)
            # marker labelling 
            ret, markers1 = cv2.connectedComponents(sure_fg)
            # add one to all labels so that sure background is not 0, but 1
            markers = markers1+1
            # Now, mark the region of unkown with zero
            markers[unknown==255] = 0

            markers3 = cv2.watershed(img, markers)
            img[markers3 == -1] = [255, 0, 0]

            b, g, r = cv2.split(img)
            imgret = cv2.merge([r,g,b])
            self.window.fs_figaxes2.clear()
            self.window.fs_figaxes2.imshow(imgret)
            self.window.fs_figaxes2.autoscale_view()
            self.window.fs_figure2.canvas.draw()

    def fens_load_src_btn_fun(self):
        fileName = self.open_image_file()
        if fileName:
            self.img = cv2.imread(fileName)
            b, g, r = cv2.split(self.img)
            imgret = cv2.merge([r,g,b])
            self.window.fs_figaxes1.clear()
            self.window.fs_figaxes1.imshow(imgret)
            self.window.fs_figaxes1.autoscale_view()
            self.window.fs_figure1.canvas.draw()

    def open_image_file(self):
        '''開啟一個影象檔案'''
        fileName, filetype= QFileDialog.getOpenFileName(self.window.page, 
            "open file", '.', "jpg Files (*.jpg);;png Files (*.png);;All Files (*)")
        return fileName


if __name__ == '__main__':

    import sys
    from PyQt5.QtWidgets import QApplication , QMainWindow

    app = QApplication(sys.argv)
    mainW = QMainWindow()
    mainW.resize(1191, 686)
    ui = grabcutWindows(mainW)
    ui.init_fun()
    mainW.show()
    sys.exit(app.exec_())

相關推薦

python for OpenCV影象處理模板匹配以及分水嶺演算法

首先看些效果如下: 具體程式碼如下: if __name__ == '__main__': from muban import Ui_Form else: from muban.muban import Ui_

Opencv影象處理---基於距離變換和分水嶺演算法影象分割

程式碼 #include <opencv2/opencv.hpp> #include <iostream> using namespace std; using namespace cv; int main(int, char** argv) {

Opencv影象處理詳解掩膜mask

1.在OpenCV中我們經常會遇到一個名字:Mask(掩膜)。很多函式都使用到它,那麼這個Mask到底什麼呢?2.如果我們想要裁剪影象中任意形狀的區域時,應該怎麼辦呢? 答案是,使用掩膜(masking)。 我們先看一下掩膜的基礎。影象的位運算。影象基本運算影象的基本運算有很

opencv影象處理滑鼠事件(矩形roi繪圖)

為滿足影象處理要求,博主寫此簡易程式碼有如下作用: 1、根據感興趣區域做深度學習標籤; 2、提取感興趣區域進行目標跟蹤; 3、對感興趣區域進行進一步操作。 具體程式碼如下: //Author: s

python實現opencv學習十三:模板匹配

模板匹配:通俗講就是以圖找圖,通過圖中的一部分來找它在圖中的位置通過三種方式來匹配:cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED程式碼如下:# -*- coding=GBK -*- import cv

opencv影象處理輪廓外背景顏色改變

自行學習弄得簡單程式碼,使用了影象中的輪廓發現以及提取,再繪製出來,改變輪廓外的畫素 首先,標頭檔案,寫的比較多,沒用的可以自己去除 #include <opencv2/core/core.hpp> #include<openc

opencv影象處理常見濾波器

影象平滑 Smoothing, also called blurring, is a simple and frequently used image processing operation. 平滑,也叫模糊. 本質就是把某點的畫素值轉換為其及其周圍畫素值的不同權重的疊加.h(k,l)即為卷積核,或

Python+OpenCV影象處理(九)—— 模板匹配

百度百科:模板匹配是一種最原始、最基本的模式識別方法,研究某一特定物件物的圖案位於影象的什麼地方,進而識別物件物,這就是一個匹配問題。它是影象處理中最基本、最常用的匹配方法。模板匹配具有自身的侷限性,主要表現在它只能進行平行移動,若原影象中的匹配目標發生旋轉或大小變化,該演算

opencvpython影象處理

一、函式簡介 1、zeros—構造全0矩陣 函式原型:zeros(shape, dtype=None, order=’C’) shape:矩陣大小;例如:300x300; dtype:資料型別;例如:”uint8” order:資料排列順序,預設按列排的 2、line—畫線

opencvpython影象處理

一、函式簡介 1、threshold—影象簡單閾值化處理 函式原型:threshold(src, thresh, maxval, type, dst=None) src:影象矩陣 thresh:閾值 maxVal:畫素最大值 type:閾值化型別 2、adaptiveThre

影象處理基於NCC模板匹配識別

一:基本原理NCC是一種基於統計學計算兩組樣本資料相關性的演算法,其取值範圍為[-1, 1]之間,而對影象來說,每個畫素點都可以看出是RGB數值,這樣整幅影象就可以看成是一個樣本資料的集合,如果它有一個子集與另外一個樣本資料相互匹配則它的ncc值為1,表示相關性很高,如果是-

使用Python+OpenCV進行圖像模板匹配(Match Template)

more 查看 AR 簡單 highlight 以及 face ims import 2017年9月22日 BY 藍鯨 LEAVE A COMMENT 本篇文章介紹使用Python和OpenCV對圖像進行模板匹配和識別。模板匹配是在圖像中尋找和識別模板的一種簡單的方法。

影象處理積分圖應用三(基於NCC快速相似度匹配演算法

影象處理之積分圖應用三(基於NCC快速相似度匹配演算法) 基於Normalized cross correlation(NCC)用來比較兩幅影象的相似程度已經是一個常見的影象處理手段。在工業生產環節檢測、監控領域對物件檢測與識別均有應用。NCC演算法可以有效降低光照對影象比較結果的影響。而

python+OpenCV影象處理(十二)車牌定位中對影象的形態學組合操作處理

車牌定位中對影象的形態學組合操作處理 所謂的車牌定位,其中最關鍵的部分就是對圖片的處理,引數的設定,並使之擁有泛化能力。 首先傳入圖片,在進行大規模的圖片處理時,因為無法確定圖片的尺寸,所以需要將原始圖片進行等比例的縮放。 orgimg = cv2.imread('ch

飛卡OpenCV影象處理賽道例項

普通寫法 程式碼 #include "cv.h" #include "highgui.h" #include <stdio.h> #include <string.h> #include <math.h> #include "

python+opencv影象處理——影象梯度——scharr運算元

sobel運算元不怎麼用,一般scharr運算元運用的比較多 import cv2 import sys import numpy as np o=cv2.imread("C:\\User

影象處理特徵提取-ORP特徵匹配

1、演算法介紹 ORB(Oriented FAST and Rotated BRIEF)是一種快速特徵點提取和描述的演算法。ORB演算法分為兩部分,分別是特徵點提取和特徵點描述。 特徵提取是由FAST(Features from  Accelerated Segment

影象處理python(基礎學習)

影象的基本處理 1. 讀取圖片 2. 儲存圖片 3. 顏色空間轉換 4. 獲取圖片屬性 5. 縮放圖片 6. 平移圖片 7. 旋轉圖片 8. 仿射變換 9. 通道的拆分/合併

影象處理其他雜項(一)MeanShift的目標跟蹤演算法opencv c++程式碼 VS2015+opencv3.2

//#include "stdafx.h" //#include "cv.h" //#include "highgui.h" #include<opencv.hpp> #define u_char unsigned char #define DIST 0.5 #define

OpenCV影象處理影象平滑

影象平滑演算法影象平滑與影象模糊是同一概念,主要用於影象的去噪。平滑要使用濾波器,為不改變影象的相位資訊,一般使用線性濾波器,其統一形式如下:其中h稱為濾波器的核函式,說白了就是權值。不同的核函式代表不同的濾波器,有不同的用途。在影象處理中,常見的濾波器包括:歸一化濾波器(H