cv2仅输出指定多边形区域 输出图片仅含多边形区域
时间: 2023-08-05 21:02:02 浏览: 44
如果你想要仅输出指定多边形区域,且输出的图片仅包含多边形区域,可以使用以下代码:
```python
import cv2
import numpy as np
# 读取图像
image = cv2.imread("image.jpg")
# 定义多边形区域的顶点坐标
pts = np.array([[50, 50], [50, 200], [200, 200], [200, 50]], np.int32)
# 创建一个透明的图像,与输入图像大小相同
mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
# 在透明图像上绘制多边形区域,将其设置为白色
cv2.fillPoly(mask, [pts], 255)
# 仅显示多边形区域
output = cv2.bitwise_and(image, image, mask=mask)
# 显示输出图像
cv2.imshow("Output", output)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
与之前的代码相比,这个示例中创建的掩膜是一个单通道的灰度图像,而不是RGBA图像。在掩膜上绘制多边形区域时,将其设置为白色。使用`cv2.bitwise_and()`函数时,将其第三个参数`mask`设置为掩膜即可。最终输出的图像仅包含多边形区域。
相关问题
100张图片作为识别训练集,每张图片内都有一个黑色框形,用python识别出并提取该框形,以棋盘格坐标,按4:6平均划分区域后,输出图片
首先,需要使用 OpenCV 库读取并处理图片,然后使用图像处理技术检测出黑色框形。可以使用以下步骤:
1. 导入所需库:
```python
import cv2
import numpy as np
```
2. 读取图片:
```python
img = cv2.imread('image.jpg')
```
3. 转换为灰度图像:
```python
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
4. 使用二值化将图像转换为黑白图像:
```python
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
```
这里使用了 Otsu 自适应二值化算法。
5. 查找轮廓并筛选出黑色框形:
```python
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
# 计算轮廓面积
area = cv2.contourArea(cnt)
if area > 1000 and area < 10000:
# 计算轮廓周长
perimeter = cv2.arcLength(cnt, True)
# 多边形逼近
approx = cv2.approxPolyDP(cnt, 0.01 * perimeter, True)
# 判断是否为矩形
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(cnt)
# 绘制矩形
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
break
```
这里使用了 findContours 函数查找轮廓,arcLength 函数计算轮廓周长,approxPolyDP 函数进行多边形逼近,boundingRect 函数计算矩形边界框。
6. 将图片划分为 4x6 的网格,并输出分割后的图片:
```python
rows, cols, _ = img.shape
row_step = rows // 4
col_step = cols // 6
for i in range(4):
for j in range(6):
roi = img[i*row_step:(i+1)*row_step, j*col_step:(j+1)*col_step]
cv2.imshow('ROI', roi)
cv2.imwrite('ROI_{}_{}.jpg'.format(i, j), roi)
cv2.waitKey(0)
```
这里使用了 shape 函数获取图片的高度和宽度,然后按照 4:6 的比例分割为若干个小区域,逐个输出。使用 imshow 函数显示分割后的小区域,使用 imwrite 函数将小区域保存为图片,使用 waitKey 函数等待用户按下任意键。
最终代码如下:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 查找轮廓并筛选出黑色框形
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 1000 and area < 10000:
perimeter = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.01 * perimeter, True)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
break
# 划分为 4x6 的网格并输出分割后的图片
rows, cols, _ = img.shape
row_step = rows // 4
col_step = cols // 6
for i in range(4):
for j in range(6):
roi = img[i*row_step:(i+1)*row_step, j*col_step:(j+1)*col_step]
cv2.imshow('ROI', roi)
cv2.imwrite('ROI_{}_{}.jpg'.format(i, j), roi)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
def Process(img): # 高斯平滑 gaussian = cv2.GaussianBlur(img, (3, 3), 0, 0, cv2.BORDER_DEFAULT)#高斯模糊函数 median = cv2.medianBlur(gaussian, 5)#中值滤波 sobel = cv2.Sobel(median, cv2.CV_8U, 1, 0, ksize=3)#Sobel算子,梯度方向是X # 二值化 ret, binary = cv2.threshold(sobel,200, 255, cv2.THRESH_BINARY)#cv2简单阙值函数 # 核函数 element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))#得到一个结构元素(卷积核)。主要用于后续的腐蚀、膨胀等运算。 element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 7)) dilation = cv2.dilate(binary, element2, iterations=1)#膨胀函数 # 腐蚀 erosion = cv2.erode(dilation, element1, iterations=1) # 膨胀 dilation2 = cv2.dilate(erosion, element2, iterations=3) return dilation2 def GetRegion(img): regions = [] # 查找轮廓 contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)#检测图像中物体轮廓 for contour in contours: area = cv2.contourArea(contour)#计算轮廓面积 if (area<2000): continue eps = 0.001* cv2.arcLength(contour, True)#计算封闭轮廓或者曲线的长度 approx = cv2.approxPolyDP(contour, eps, True)#轮廓多边形逼近 rect = cv2.minAreaRect(contour)#求最小面积矩形框 box = cv2.boxPoints(rect)#获取最小面积矩形框的四个顶点坐标 box = np.int0(box)#整型化 height = abs(box[0][1] - box[2][1]) width = abs(box[0][0] - box[2][0]) ratio =float(width) / float(height) if (ratio < 5 and ratio > 1.8): regions.append(box) return regions def detect(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#图片灰度化 prc = Process(gray) regions = GetRegion(prc) print('[INFO]:Detect %d license plates' % len(regions)) for box in regions: cv2.drawContours(img, [box], 0, (0, 0,255), 2) cv2.imwrite(r'C:\Users\86182\Pictures\Saved Pictures\test.png', img) cv2.waitKey(0) cv2.destroyAllWindows()该代码在实现车牌区域检测的过程中用到了什么算法
这段代码实现车牌区域检测主要用到了以下算法:
1. 高斯平滑(GaussianBlur)和中值滤波(medianBlur):用于平滑图像,减少噪声的影响。
2. Sobel算子(Sobel):用于检测图像边缘。
3. 二值化(threshold):将图像转换为黑白两色,方便后续处理。
4. 膨胀(dilate)和腐蚀(erode):用于调整图像形态,填补边缘空洞,去除小的噪点等。
5. 轮廓查找(findContours)和轮廓逼近(approxPolyDP):用于识别图像中的轮廓,并将其逼近为多边形。
6. 最小面积矩形框(minAreaRect):用于求出包含轮廓的最小面积矩形框。
7. 整型化(np.int0):将浮点型数据转换为整型数据。
8. 输出识别到的车牌数量,并将标记后的图像保存在本地。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)