图像直边外接矩形 python
时间: 2023-07-08 12:36:45 浏览: 36
您好!要获取图像的直边外接矩形,可以使用 OpenCV 库中的 `findContours()` 函数和 `boundingRect()` 函数来实现。
以下是示例代码:
```python
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 获取二值化图像
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 获取轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 获取直边外接矩形
x, y, w, h = cv2.boundingRect(contours[0])
# 在图像上绘制矩形
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,首先读取图像并将其转换为灰度图像。然后通过二值化图像获取轮廓,并使用 `boundingRect()` 函数获取轮廓的直边外接矩形。最后在原始图像上绘制矩形并显示图像。
希望能帮到您!
相关问题
透明图像直边外接矩形提取代码
以下是Python中使用OpenCV库实现透明图像直边外接矩形提取的代码:
```python
import cv2
# 读取图像
img = cv2.imread("transparent_image.png", cv2.IMREAD_UNCHANGED)
# 提取 alpha 通道
alpha = img[:, :, 3]
# 找到 alpha 通道不为 0 的像素点的坐标
points = cv2.findNonZero(alpha)
# 计算外接矩形
rect = cv2.boundingRect(points)
# 在图像上绘制矩形
cv2.rectangle(img, (rect[0], rect[1]), (rect[0]+rect[2], rect[1]+rect[3]), (0, 0, 255), 2)
# 显示图像
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`cv2.imread`函数用于读取图像,`cv2.IMREAD_UNCHANGED`表示读取包含 alpha 通道的图像。`cv2.findNonZero`函数用于找到 alpha 通道不为 0 的像素点的坐标,`cv2.boundingRect`函数用于计算外接矩形。最后,使用`cv2.rectangle`函数在图像上绘制矩形,并使用`cv2.imshow`函数显示图像。
透明图像直边外接矩形提取并裁剪保存代码
以下是Python中使用OpenCV库实现透明图像直边外接矩形提取并裁剪保存的代码:
```python
import cv2
# 读取图像
img = cv2.imread("transparent_image.png", cv2.IMREAD_UNCHANGED)
# 提取 alpha 通道
alpha = img[:, :, 3]
# 找到 alpha 通道不为 0 的像素点的坐标
points = cv2.findNonZero(alpha)
# 计算外接矩形
rect = cv2.boundingRect(points)
# 裁剪图像
crop_img = img[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2]]
# 保存裁剪后的图像
cv2.imwrite("crop_image.png", crop_img)
# 在原图像上绘制矩形
cv2.rectangle(img, (rect[0], rect[1]), (rect[0]+rect[2], rect[1]+rect[3]), (0, 0, 255), 2)
# 保存带有矩形的图像
cv2.imwrite("rect_image.png", img)
# 显示图像
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`crop_img = img[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2]]`用于裁剪图像,`cv2.imwrite`函数用于保存裁剪后的图像和带有矩形的图像。完整代码实现了同时保存裁剪后的图像和包含矩形的原图像。