opencv detected_edges
原文链接: opencv detected_edges
轮廓检测
OpenCV中几何形状识别与测量-流浪的鱼-51CTO博客
计算极值
pentagram = contours[1] #第二条轮廓是五角星
leftmost = tuple(pentagram[:,0][pentagram[:,:,0].argmin()])
rightmost = tuple(pentagram[:,0][pentagram[:,:,0].argmin()])
cv2.circle(img, leftmost, 2, (0,255,0),3)
cv2.circle(img, rightmost, 2, (0,0,255),3)
获取标记图片的坐标
img = cv2.imread("1.jpg")
hight, width, depth = img.shape[0:3]
# 图片二值化处理,把[240, 240, 240]~[255, 255, 255]以外的颜色变成0
thresh = cv2.inRange(img, np.array([0, 0, 190]), np.array([40, 40, 255]))
# 创建形状和尺寸的结构元素
kernel = np.ones((2, 2), np.uint8)
kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
# 膨胀扩张待修复区域, 使间断区域闭合
hi_mask = cv2.dilate(thresh, kernel, iterations=2)
specular = cv2.inpaint(img, hi_mask, 5, flags=cv2.INPAINT_TELEA)
# 有先经过 高斯滤波处理 去除噪声
pic = cv2.GaussianBlur(src=pic, ksize=(5, 5), sigmaX=0, sigmaY=0)
import cv2
import numpy as np
class Shape():
def __init__(self, color, shape, x, y, approx):
self.color = color
self.shape = shape
self.x = x
self.y = y
self.approx = approx
def closing(mask):
kernel = np.ones((7,7),np.uint8)
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
return closing
def opening(mask):
kernel = np.ones((6,6),np.uint8)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
return opening
#Define Red
lower_red = np.array([0, 90, 60], dtype=np.uint8)
upper_red = np.array([10, 255, 255], dtype=np.uint8)
red = [lower_red, upper_red, 'red']
#Define Green
lower_green = np.array([60, 55, 0], dtype=np.uint8)
upper_green = np.array([100, 255, 120], dtype=np.uint8)
green = [lower_green, upper_green, 'green']
#Define Blue
lower_blue = np.array([90, 20, 60], dtype=np.uint8)
upper_blue = np.array([130, 255, 180], dtype=np.uint8)
blue = [lower_blue, upper_blue, 'blue']
#Define Yellow
lower_yellow = np.array([5, 110, 200], dtype=np.uint8)
upper_yellow = np.array([50, 255, 255], dtype=np.uint8)
yellow = [lower_yellow, upper_yellow, 'yellow']
#Define White
lower_white = np.array([0, 90, 60], dtype=np.uint8)
upper_white = np.array([10, 255, 255], dtype=np.uint8)
white = [lower_white, upper_white ,'white']
colors = [red, green, blue, yellow, white]
def detect_shapes(image_location):
#Open image
img = cv2.imread(image_location)
#Convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#Shape list
shapes = []
#Lay over masks and detect shapes
for color in colors:
mask = cv2.inRange(hsv, color[0], color[1])
mask = closing(mask)
mask = opening(mask)
contours, h = cv2.findContours(mask, 1, cv2.CHAIN_APPROX_SIMPLE)
contours.sort(key = len)
for contour in contours[-3:]:
#Amount of edges
approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour, True), True)
#Center locations
M = cv2.moments(contour)
if M['m00'] == 0.0:
continue
centroid_x = int(M['m10']/M['m00'])
centroid_y = int(M['m01']/M['m00'])
if len(approx) == 4:
shape_name = 'rectangle'
elif len(approx) == 10:
shape_name = 'star'
elif len(approx) >= 11:
shape_name = 'oval'
else:
shape_name ='undefined'
shape = Shape(color[2], shape_name, centroid_x, centroid_y, len(approx))
shapes.append(shape)
return shapes
import cv2
import numpy as np
import matplotlib.pyplot as pyplot
# reading the image
image = cv2.imread("im1.png")
imb = cv2.resize(image, (960, 340))
imb1 = cv2.resize(image, (960, 340))
imb = cv2.cvtColor(imb, cv2.COLOR_RGB2GRAY)
cv2.imshow("rey", imb)
cv2.waitKey(0)
ret, imb = cv2.threshold(imb, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("hi", imb)
cv2.waitKey(0)
kernel = np.ones((15, 15), np.uint8)
erosion = cv2.erode(imb, kernel, iterations=1)
cv2.imshow('erosion', erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
# DIALATION OF IMAGE AND MORPHOLOGICAL OPENING
dilation = cv2.dilate(erosion, kernel, iterations=2)
cv2.imshow('dilation', dilation)
#cv2.waitKey(0)
cv2.destroyAllWindows()
edged = cv2.Canny(dilation, 10, 250)
cv2.imshow("Edges", edged)
#cv2.waitKey(0)
# applying closing function
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)
cv2.imshow("Closed", closed)
cv2.waitKey(0)
cv2.destroyAllWindows()
# finding_contours
count=0
index=0
(_,cnts,_) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
s_no=np.zeros((4))
o_cnts_x=np.zeros((3))
cnts_x=np.zeros((3))
o_cnts=np.zeros((3,4))
contours = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in contours :
if count < 3:
x, y, w, h = cv2.boundingRect(c)
cnts_x[count]=x
count = count + 1
o_cnts_x=sorted(cnts_x)
count=0
for c in contours :
if count < 3:
x, y, w, h = cv2.boundingRect(c)
if o_cnts_x[0]==x:
o_cnts[0]=cv2.boundingRect(c)
s1 = imb1[y - 5:y + h + 5, x - 15:x + w + 5]
count=count+1
count=0
for c in contours:
if count < 3:
x, y, w, h = cv2.boundingRect(c)
x, y, w, h = cv2.boundingRect(c)
if o_cnts_x[1] == x:
o_cnts[1] = cv2.boundingRect(c)
s2 = imb1[y - 5:y + h + 5, x - 15:x + w + 5]
count = count + 1
count=0
for c in contours:
if count < 3:
x, y, w, h = cv2.boundingRect(c)
if o_cnts_x[2] == x:
o_cnts[2] = cv2.boundingRect(c)
s3 = imb1[y - 5:y + h + 5, x - 15:x + w + 5]
count = count + 1
print("ordered cnts")
print(o_cnts)
#cv2.rectangle(dilation, (x - 15, y - 5), (x + w + 5, y + h + 5), (0, 255, 0), 2)
cv2.imshow('s1', s1)
cv2.imshow('s2', s2)
cv2.imshow('s3', s3)
cv2.waitKey(0)
cv2.waitKey(0)
'''''
for c in contours:
count=count+1
if count<4 :
index = 0
for main_c in cnts :
#print(cv2.boundingRect(c),cv2.boundingRect(main_c))
if cv2.boundingRect(c)==cv2.boundingRect(main_c) :
s_no[count]=index
print(cv2.boundingRect(c), cv2.boundingRect(main_c))
index = index + 1
print(s_no)
s_no=sorted(s_no)
index_cnts=0
for c in cnts:
if (s_no[1]) == index_cnts :
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(dilation, (x - 15, y - 5), (x + w + 5, y + h + 5), (0, 255, 0), 2)
s = imb1[y - 5:y + h + 5, x - 15:x + w + 5]
filename = "s1.jpg"
cv2.imwrite(filename, s)
cv2.imshow("Output", s)
cv2.waitKey(0)
index_cnts = index_cnts + 1
index_cnts=0
for c in cnts:
if (s_no[2]) == index_cnts :
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(dilation, (x - 15, y - 5), (x + w + 5, y + h + 5), (0, 255, 0), 2)
s = imb1[y - 5:y + h + 5, x - 15:x + w + 5]
filename = "s2.jpg"
cv2.imwrite(filename, s)
cv2.imshow("Output", s)
cv2.waitKey(0)
index_cnts = index_cnts + 1
'''
'''''
cv2.rectangle(dilation, (x-15 , y-5), (x + w+5, y + h+5), (0, 255, 0), 2)
s = imb1[y-5:y+h+5, x-15:x+w+5]
filename = "s%d.jpg" %count
print(filename)
cv2.imwrite(filename,s)
cv2.imshow("Output", s)
cv2.waitKey(0)
'''''
#print(s_no)
#cv2.imshow("Output", dilation)
#cv2.waitKey(0)
'''''
_,contours,_ = cv2.findContours(closed,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(imb1,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow("Show",imb1)
cv2.imwrite("imaes/img5_rect.jpg", imb1 )
contours,hierarchy = cv2.findContours(closed,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
crop = imb1[y:y+h,x:x+w]
cv2.imwrite('sofwinres.png',crop)
'''
cv2.waitKey(0)