【发布时间】:2019-11-04 12:56:57
【问题描述】:
我有一张在深色背景中有一张嘴巴照片的输入图像: input image
我只想要嘴部分作为输出: output image
【问题讨论】:
-
考虑使用image processing library,如 PIL/Pillow。
标签: python image opencv image-processing python-imaging-library
我有一张在深色背景中有一张嘴巴照片的输入图像: input image
我只想要嘴部分作为输出: output image
【问题讨论】:
标签: python image opencv image-processing python-imaging-library
试试这个Crop black edges with OpenCV
import numpy as np
import cv2
img = cv2.imread('./data/q18.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#play with parameters that all I changed in answer
_,thresh = cv2.threshold(gray,20,255,cv2.THRESH_BINARY)
# and here are 3 value returned not 2
_,contours,_ = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
crop = img[y:y+h,x:x+w]
cv2.imwrite('./data/q18_1.png',crop)
输出:
【讨论】:
使用https://scikit-image.org/ 库。您可以像下面这样简单地裁剪它。
from skimage import io
image = io.imread(filename)
cropped = image[x1:x2,y1:y2]
【讨论】:
像这样使用 PIL/Pillow:
#!/usr/bin/env python3
from PIL import Image
# Load image and convert to greyscale
im = Image.open('mouth.png').convert('L')
# Threshold at 40
thr = im.point(lambda p: p > 40 and 255)
# Find bounding box
bbox = thr.getbbox()
# Debug
print(bbox)
# Crop and save
result = im.crop(bbox)
result.save('result.png')
样本输出
(70, 155, 182, 223)
【讨论】: