Pyhton3+openCV3初体验

Posted lc__________

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pyhton3+openCV3初体验相关的知识,希望对你有一定的参考价值。

其中python3采用的anaconda进行Python的安装与库的管理。

安装好anaconda后,就可以通过anaconda来安装opencv了。打开Anaconda Prompt命令行程序,输入conda list,可以查看已安装的库。

输入conda install --channel https://conda.anaconda.org/menpo opencv3 可以对opencv进行安装。


安装好的环境通过测试表明安装无误~

import cv2
import numpy as np

#找到输入图像中接近于圆的blob
def getBlob(img):
    step = 0.05
    # Setup SimpleBlobDetector parameters.
    params = cv2.SimpleBlobDetector_Params()
    # Change thresholds
    params.minThreshold = 10;
    params.maxThreshold = 200;
    # Filter by Area.
    params.filterByArea = True
    params.minArea = 500
    # Filter by Circularity
    params.filterByCircularity = True
    params.minCircularity = 0.8
    # Filter by Convexity
    params.filterByConvexity = True
    params.minConvexity = 0.87
    # Filter by Inertia
    params.filterByInertia = True
    params.minInertiaRatio = 0.01
    # Set up the detector with default parameters.
    ver = (cv2.__version__).split('.')
    if int(ver[0]) < 3 :
        detector = cv2.SimpleBlobDetector(params)
    else : 
        detector = cv2.SimpleBlobDetector_create(params)
    # Detect blobs.
    keypoints = detector.detect(img)
    #print (keypoints,type(keypoints[0]))
    #圆度限制为0.8.若只找到一个圆则返回。若未找到圆则降低圆度限制再试一次。若找到多个,则返回半径最接近的。
    if len(keypoints) == 1:
        if keypoints[0].size >26 and keypoints[0].size < 34:            
            return [int(keypoints[0].pt[0]), int(keypoints[0].pt[1])]
        else:
            return [0,0]
    else:
        #调整圆度限制,再找一次blob
        if len(keypoints) > 1:
            params.minCircularity = params.minCircularity + step
        else:
            params.minCircularity = params.minCircularity - step
        if int(ver[0]) < 3:
            detector = cv2.SimpleBlobDetector(params)
        else : 
            detector = cv2.SimpleBlobDetector_create(params)
        keypoints = detector.detect(img)
        if len(keypoints) == 1:
            if keypoints[0].size >26 and keypoints[0].size < 34:            
                return [int(keypoints[0].pt[0]), int(keypoints[0].pt[1])]
            else:
                return [0,0]
        elif len(keypoints) == 0:
            return [0,0]
        else:
            minR = 100
            pointXY = []
            for i in range(len(keypoints) - 1):
                if abs(keypoints[i].size - 30) > minR:
                    pointXY = [int(keypoints[i].pt[0]), int(keypoints[i].pt[1])]
                    minR = abs(keypoints[i].size - 30)
            return pointXY

def getCirclesByHoughCircles(img):
    #canny边缘检测
    image = cv2.Canny(image3, 200, 300)
    print ("边缘检测后",image[120,114], image[120,115], image[120,116], image[120,117], image[120,118], image[120,119], image[120,120])

    #保存图片
    #cv2.imwrite("canny.jpg", cv2.Canny(image, 200, 300))
    #弹出窗口显示图片
    #cv2.imshow("image", image)
    #cv2.waitKey (0)
    #cv2.destroyAllWindows()  

    #houghCircles查找圆
    #HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) -> circles
    #params-image:灰度图
    #params-method:使用的检测方法
    #params-dp:累加器。1表示累加器和输入图像有相同的分辨率。2表示累加器有输入图像高宽的一半大小
    #params-minDist:两个不同圆之间的最小距离
    #params-params1:
    #params-params2:
    #params-minRadius:圆半径的最小值
    #params-maxRadius:圆半径的最大值
    circlesHoughCirResult = cv2.HoughCircles(topLeftRoi, cv2.HOUGH_GRADIENT, 10, 50, param1=100, param2=100, minRadius=10, maxRadius=40)
    print ("HoughCircles找到的结果:",circlesHoughCirResult.shape)
    #该算法可能会找到很多根本不存在的圆。所以我们接下来计算圆度,来筛选出符合要求的圆
    circlesHoughCirResult_check = []
    for i in range(circlesHoughCirResult[:,:,0].size):    
        if image3[int(circlesHoughCirResult[:,i,:][0,0]),int(circlesHoughCirResult[:,i,:][0,1])] == 0 and circlesHoughCirResult[:,i,:][0,2] > 13 and circlesHoughCirResult[:,i,:][0,2] < 17:
            circlesHoughCirResult_check.append(circlesHoughCirResult[:,i,:])
    return circlesHoughCirResult_check

#加载图片,imread第二个参数为0表示读入的为灰度图
image3=cv2.imread('Y:/1.tif',0)
print ("opencv加载后的数组类型:",type(image3),";","数组形状:",image3.shape)

#自适应阈值二值化
#adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
#params-src:原始图像
#params-maxValue:像素的上限值
#params-adaptiveMethod:自适应的方法。
    #cv2.ADAPTIVE_THRESH_MEAN_C为邻域内均值、cv2.ADAPTIVE_THRESH_GAUSSIAN_C为邻域内像素点加权和,权重为一个高斯窗口
#params-thresholdType:赋值方法。cv2.THRESH_BINARY 和cv2.THRESH_BINARY_INV
#params-blockSize:邻域大小
#params-C[,dst]:常数C。阈值等于均值或者加权值减去这个常数。
image2 = cv2.adaptiveThreshold(image3, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 2)

#img[高,宽]
print (image2[120,114], image2[120,115], image2[120,116], image2[120,117], image2[120,118], image2[120,119], image2[120,120])
topLeftRoi = image2[:300,:300]
#霍夫变换找圆
circlesHoughCirResult_check = getCirclesByHoughCircles(topLeftRoi)
print (circlesHoughCirResult_check)
topLeftRoi = cv2.Canny(topLeftRoi, 200, 300)
print (getBlob(topLeftRoi))

输出:

opencv加载后的数组类型: <class 'numpy.ndarray'> ; 数组形状: (2232, 1584)
255 255 0 0 0 0 0
边缘检测后 0 255 0 0 0 0 0
HoughCircles找到的结果: (1, 6, 3)
[array([[ 125.        ,  125.        ,   14.14213467]], dtype=float32)]
[127, 125]

以上是关于Pyhton3+openCV3初体验的主要内容,如果未能解决你的问题,请参考以下文章

libtorch初体验

OpenCV3编程入门-读书笔记3-滤波

PCL:RadiusOutlierRemoval ❤️ 半径滤波

MATLAB 向量化:计算邻域矩阵

初探DBSCAN聚类算法

多元函数