利用python3和opencv去掉图片黑边
时间: 2023-06-28 20:12:49 浏览: 179
可以通过以下步骤使用Python和OpenCV去掉图片的黑边:
1. 导入必要的库
```
import cv2
import numpy as np
```
2. 读取图片
```
img = cv2.imread('image.jpg')
```
3. 将图片灰度化
```
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
4. 对图片进行二值化处理
```
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
```
5. 查找图片边缘
```
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
```
6. 找到图片最大的边缘
```
c = max(cnts, key=cv2.contourArea)
```
7. 获取最大边缘的坐标范围
```
x,y,w,h = cv2.boundingRect(c)
```
8. 截取去掉黑边的图片
```
crop = img[y:y+h, x:x+w]
```
9. 显示截取后的图片
```
cv2.imshow('crop', crop)
cv2.waitKey()
```
完整代码如下:
```
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
c = max(cnts, key=cv2.contourArea)
x,y,w,h = cv2.boundingRect(c)
crop = img[y:y+h, x:x+w]
cv2.imshow('crop', crop)
cv2.waitKey()
```
阅读全文