opencv principle
import cv2 as cv
img = cv.imread('a.png',1)
cv.imshow('image',img)
cv.imwrite('b.jpg',img,[cv.IMWRITE_JPEG_QUALITY,0])
cv.imwrite('b.png',img,[cv.IMWRITE_PNG_COMPRESSION,0])
img = cv.imread('a.png',1)
(b,g,r) = img[200,200]
print(b,g,r)
for i in range(1,100):
img[10+i,100] = (255,0,0)
cv.imshow('image',img)
cv.waitKey(0)
Filter background function:
def select_rgb_white_yellow(self,image):
lower = np.uint8([120, 120, 120])
upper = np.uint8([255, 255, 255])
white_mask = cv2.inRange(image, lower, upper)
self.cv_show('white_mask',white_mask)
masked = cv2.bitwise_and(image, image, mask = white_mask)
self.cv_show('masked',masked)
return masked
Custom area of interest
def select_region(self,image):
"""
感兴趣边界每一条边都会有对应的端点 我们把这些点拿出来连成线就得到了感兴趣区域
"""
rows, cols = image.shape[:2]
pt_1 = [cols*0.05, rows*0.90]
pt_2 = [cols*0.05, rows*0.70]
pt_3 = [cols*0.30, rows*0.55]
pt_4 = [cols*0.6, rows*0.15]
pt_5 = [cols*0.90, rows*0.15]
pt_6 = [cols*0.90, rows*0.90]
vertices = np.array([[pt_1, pt_2, pt_3, pt_4, pt_5, pt_6]], dtype=np.int32)
point_img = image.copy()
point_img = cv2.cvtColor(point_img, cv2.COLOR_GRAY2RGB)
for point in vertices[0]:
cv2.circle(point_img, (point[0],point[1]), 10, (0,0,255), 4)
self.cv_show('point_img',point_img)
return self.filter_region(image, vertices)
Filter out unwanted places
def filter_region(self,image, vertices):
"""
过滤掉不需要的地方
"""
mask = np.zeros_like(image)
if len(mask.shape)==2:
cv2.fillPoly(mask, vertices, 255)
self.cv_show('mask', mask)
return cv2.bitwise_and(image, mask)
Hough line detection Api
def hough_lines(self,image):
return cv2.HoughLinesP(image, rho=0.1, theta=np.pi/10, threshold=15, minLineLength=9, maxLineGap=4)
Filter line segments and draw
def draw_lines(self,image, lines, color=[255, 0, 0], thickness=2, make_copy=True):
if make_copy:
image = np.copy(image)
cleaned = []
for line in lines:
for x1,y1,x2,y2 in line:
if abs(y2-y1) <=1 and abs(x2-x1) >=25 and abs(x2-x1) <= 55:
cleaned.append((x1,y1,x2,y2))
cv2.line(image, (x1, y1), (x2, y2), color, thickness)
print(" No lines detected: ", len(cleaned))
return image
Crop pictures for network training
裁剪图片,用于网络训练:
def save_images_for_cnn(self,image, spot_dict, folder_name ='cnn_data'):
for spot in spot_dict.keys():
(x1, y1, x2, y2) = spot
(x1, y1, x2, y2) = (int(x1), int(y1), int(x2), int(y2))
spot_img = image[y1:y2, x1:x2]
spot_img = cv2.resize(spot_img, (0,0), fx=2.0, fy=2.0)
spot_id = spot_dict[spot]
filename = 'spot' + str(spot_id) +'.jpg'
print(spot_img.shape, filename, (x1,x2,y1,y2))
cv2.imwrite(os.path.join(folder_name, filename), spot_img)