opencv 杂记

# 调整图像大小
size = (width, height)
img = cv2.resize(img_src, size, interpolation=cv2.INTER_CUBIC)


# 转化为HSV图像

HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# 提取红色区域
# LowerBlue = np.array([0, 43, 46])
# UpperBlue = np.array([10, 255, 255])
# LowerRed = np.array([156, 43, 46])
# UpperRed = np.array([180, 255, 255])
# 提取绿色区域
LowerGreen = np.array([11, 43, 46])
UpperGreen = np.array([99, 255, 255])
mask = cv2.inRange(HSV, LowerGreen, UpperGreen)
filtered_area = mask
# 寻找轮廓
binary, contours, hierarchy = cv2.findContours(filtered_area, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 创建空白图像并用于绘制所找到的轮廓
empty_img = np.zeros(img.shape, np.uint8)
cv2.drawContours(empty_img, [contour], -1, (255, 255, 255), 1)
# 直线检测 1

gray = cv2.cvtColor(empty_img, cv2.COLOR_BGR2GRAY)
lines = cv2.HoughLinesP(gray, 1, np.pi / 180, int(width * 0.1), int(width * 0.5))

for line in lines:
    [[x1, y1, x2, y2]] = line

    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

# hough transform

lines = cv2.HoughLines(gray, 1, np.pi / 180, 160)
# 提取为为二维
lines = lines[:, 0, :]
# 需要检查是否为四条直线
logger.info("检测出%s条直线" % len(lines))
my_lines = []
my_points = []
dis = []
for rho, theta in lines[:]:
    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), (255, 0, 0), 1)


# 形态学操作
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
# 第二个参数:要执行的形态学操作类型,这里是bi操作
# filtered_area = cv2.morphologyEx(filtered_area, cv2.MORPH_CLOSE, kernel)
# filtered_area = cv2.morphologyEx(filtered_area, cv2.MORPH_CLOSE, kernel)
# cv2.imwrite("r_close.jpg", filtered_area)
# print("原始大小:%d - %d" % (width, height))
cv2.imwrite("r.jpg", img)
# 创建窗口并显示图像
cv2.namedWindow("Image")
cv2.imshow("Image", img)
cv2.waitKey(0)
# 释放窗口
cv2.destroyAllWindows()

你可能感兴趣的:(opencv 杂记)