程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python blob detection dot

編輯:Python

blob Only black spots on the inside and white spots on the outside can be detected

If you want to detect white spots inside and black spots outside , Then the image should be inverted

img_inv = 255 - img

Original picture

 

Test result chart

plt

 opencv

 

# coding:utf-8
import math
import cv2
import numpy as np
import xml.etree.ElementTree as ET
import random
import matplotlib.pyplot as plt
def get_distance_point2line(point, line_ab): # Find the distance from the point to the straight line
"""
Args:
point: [x0, y0]
line_ab: [k, b]
"""
k, b = line_ab
distance = abs(k * point[0] - point[1] + b) / math.sqrt(k ** 2 + 1)
return distance
# Vertical and horizontal lines are not considered
def drawLines(img, allCirclesCenter):
# Calculate the centerline of two rows of points
nptest = np.array(allCirclesCenter)
line = cv2.fitLine(nptest, cv2.DIST_L2, 0, 0.001, 0.0)
# print(line)
k = line[1] / line[0]
b = line[3] - k * line[2]
# If it is a horizontal line
if k <= 10e-5:
pass
# If it is vertical
if k > 10e5:
pass
print('y = {:0.8f}x + {:0.8f}'.format(k[0], b[0]))
ptStart, ptEnd = (0, int(k * 0 + b)), (img.shape[1], int(k * img.shape[1] + b))
# The coordinate point needs to be modified to obtain an integer *************** Draw a line that covers the whole picture
cv2.line(img, ptStart, ptEnd, (0, 0, 255), thickness=2, lineType=3)
# cv2.imshow("line", img)
# cv2.waitKey()
# Distinguish the upper and lower points , Fit two straight lines
line1_yx, line2_yx = [], []
for i in allCirclesCenter:
if i[1] < float(k * i[0] + b):
line1_yx.append(i)
else:
line2_yx.append(i)
# line1 Find the first straight line
nptest1 = np.array(line1_yx)
line1 = cv2.fitLine(nptest1, cv2.DIST_L2, 0, 0.01, 0.0)
k1 = line1[1] / line1[0]
b1 = line1[3] - k1 * line1[2]
# print(line1)
print('line1')
print('y = {:0.8f}x + {:0.8f}'.format(k1[0], b1[0]))
for i in line1_yx: # Display the distance from the point to the line
point = i
line_ = k1, b1
dis = get_distance_point2line(point, line_)
# print(' distance : ' + str(dis))
ptStart, ptEnd = (0, int(k1 * 0 + b1)), (img.shape[1], int(k1 * img.shape[1] + b1))# The coordinate point needs to be modified to obtain an integer ***************
cv2.line(img, ptStart, ptEnd, ( 255, 0, 0), 2)
# cv2.imshow("line1", img)
# lin2 Find the second straight line
nptest2 = np.array(line2_yx)
line2 = cv2.fitLine(nptest2, cv2.DIST_L2, 0, 0.01, 0.0)
k2 = line2[1] / line2[0]
b2 = line2[3] - k2 * line2[2]
# print(line2)
print('line2')
print('y = {:0.8f}x + {:0.8f}'.format(k2[0], b2[0]))
ptStart, ptEnd = (0, int(k2 * 0 + b2)), (img.shape[1], int(k2 * img.shape[1] + b2)) # The coordinate point needs to be modified to obtain an integer ***************
cv2.line(img, ptStart, ptEnd, ( 255, 0, 0), 2) # The pixel value must be an integer ****************
# cv2.imshow("line2", img)
# cv2.waitKey()
imgNormal = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(imgNormal)
plt.show()
def mainFigure(img):
paramsOut = cv2.SimpleBlobDetector_Params()
# Setup SimpleBlobDetector parameters.
# print('params')
# print(params)
# print(type(params))
# Filter by Area.
paramsOut.filterByArea = True
paramsOut.minArea = 5000
paramsOut.maxArea = 10e3
paramsOut.minDistBetweenBlobs = 25
paramsOut.filterByColor = True
paramsOut.filterByConvexity = False
paramsOut.minThreshold = 10
paramsOut.maxThreshold = 30*2.5
# tweak these as you see fit
# Filter by Circularity
# params.filterByCircularity = False
# params.minCircularity = 1
# params.blobColor = 0
# # # Filter by Convexity
# params.filterByConvexity = True
# params.minConvexity = 1
# Filter by Inertia
# params.filterByInertia = True
# params.filterByInertia = False
# params.minInertiaRatio = 0.1
gray_src= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Detect blobs.
# image = cv2.resize(gray_img, (int(img.shape[1]/4),int(img.shape[0]/4)), 1, 1, cv2.INTER_LINEAR)
# image = cv2.resize(gray_img, dsize=None, fx=0.25, fy=0.25, interpolation=cv2.INTER_LINEAR)
minThreshValue = 35
_, gray = cv2.threshold(gray_src, minThreshValue, 255, cv2.THRESH_BINARY)
gray = cv2.resize(gray, dsize=None, fx=1, fy=1, interpolation=cv2.INTER_LINEAR)
# cv2.imshow("gray1",gray)
kernel = np.ones((3, 3), dtype=np.uint8)
gray = cv2.dilate(gray, kernel, 1) # 1: The number of iterations , That is, perform several expansion operations
gray = cv2.erode(gray, kernel, 1)
# plt.imshow(gray)
# cv2.imshow("gray",gray)
# Find the origin (0,0) Nearest and farthest point
# Detect outer circle
detector = cv2.SimpleBlobDetector_create(paramsOut)
keypoints = detector.detect(gray)
# opencv
im_with_keypoints = cv2.drawKeypoints(gray, keypoints, np.array([]), (255, 0, 0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# im_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DEFAULT)
# print(keypoints)
# cv2.imshow("zero_gray", gray)
# Detect the inner circle Image reversal
paramsIn = cv2.SimpleBlobDetector_Params()
paramsIn.filterByArea = True
paramsIn.minArea = 100
paramsIn.maxArea = 500
paramsIn.minDistBetweenBlobs = 10
paramsIn.filterByColor = True
paramsIn.filterByConvexity = False
paramsIn.minThreshold = 30
paramsIn.maxThreshold = 30*2.5
# Image reversal
needleGray = 255 - gray.copy()
cv2.imshow('needleGray', needleGray)
detector2 = cv2.SimpleBlobDetector_create(paramsIn)
needleKeypoints = detector2.detect(needleGray)
# opencv
needle_keypoints = cv2.drawKeypoints(needleGray, needleKeypoints, np.array([]), (255, 0, 0),
cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
allNeedlePoints = []
if keypoints is not None:
for i in range(len(needleKeypoints)):
allNeedlePoints.append(needleKeypoints[i].pt)
# Impossible, most of them are oblique , Fit directly according to most point sets
# print(allCirclesCenter)
# if allCirclesCenter is not None:
if len(allNeedlePoints) > 10:
drawLines(needle_keypoints, allNeedlePoints)
color_img = cv2.cvtColor(im_with_keypoints, cv2.COLOR_BGR2RGB)
needle_img = cv2.cvtColor(needle_keypoints, cv2.COLOR_BGR2RGB)
cv2.imshow('holeShow', color_img)
cv2.imshow('needleShow', needle_img)
cv2.waitKey()
if __name__ == "__main__":
# # # Single picture test
# img = cv2.imread("images/HenFeng/HF01.jpg",1)
# img = cv2.imread("images/Snap_0.jpg",1)
# img = cv2.imread("images/Holes/Hole2.jpg",1)
# mainFigure(img)
# # All picture tests
for i in range(5):
fileName = "Zhen" + str(i+1) + ".jpg"
# img = cv2.imread("circles/Snap_007.jpg",1)
img = cv2.imread("images/ZhenJiao/" + fileName,1)
print(fileName)
mainFigure(img)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved