|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区
您需要 登录 才可以下载或查看,没有账号?立即注册
×
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import cv2
# 读取图片
rawImage = cv2.imread("img\car.jpg")
cv2.imshow('image01', rawImage)
# 高斯模糊,将图片平滑化,去掉干扰的噪声
image= cv2.GaussianBlur(rawImage, (3, 3), 0)
cv2.imshow('image02', image)
# 图片灰度化
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
cv2.imshow('image03', image)
# Sobel算子(XY方向)图像边缘检测。
Sobel_x = cv2.Sobel(image, cv2.CV_16S, 1, 0)
absX = cv2.convertScaleAbs(Sobel_x) # 转回uint8
Sobel_y = cv2.Sobel(image, cv2.CV_16S, 0, 1)
absY = cv2.convertScaleAbs(Sobel_y)
dst = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
cv2.imshow('image04', dst)
image = dst
# 二值化:图像的二值化,就是将图像上的像素点的灰度值设置为0或255,图像呈现出明显的只有黑和白
ret, image = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU)
cv2.imshow('image05', image)
# 闭操作:闭操作可以将目标区域连成一个整体,便于后续轮廓的提取。
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 5))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX)
cv2.imshow('image06', image)
# 膨胀腐蚀(形态学处理)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 19))
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
cv2.imshow('image07', image)
# 平滑处理,中值滤波
image = cv2.medianBlur(image, 15)
cv2.imshow('image8', image)
# 边缘检测
image = cv2.Canny(image, 50, 150)
cv2.imshow('image9', image)
# 查找轮廓
contours,wi= cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for item in contours:
rect = cv2.boundingRect(item)
print(rect)
x = rect[0]
y = rect[1]
weight = rect[2]
height = rect[3]
if weight > (height * 2):
# 裁剪区域图片
chepai = rawImage[y:y + height, x:x + weight]
cv2.imshow('chepai'+str(x), chepai)
# 绘制轮廓
image = cv2.drawContours(rawImage, contours, -1, (0, 0, 255), 3)
cv2.imshow('image10', image)
cv2.waitKey(0)
cv2.destroyAllWindows() |
|