如何在python中切片图像的特定部分?

时间:2019-11-04 12:56:57

标签: python image opencv image-processing python-imaging-library

我有一个输入图像,其中的一张嘴照片在深色背景中: input image

我只希望口部分作为输出: output image

3 个答案:

答案 0 :(得分:0)

使用https://scikit-image.org/库。您可以像下面这样轻松裁剪。

from skimage import io
image = io.imread(filename)
cropped = image[x1:x2,y1:y2]

答案 1 :(得分:0)

尝试这个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)

输出:

enter image description here

答案 2 :(得分:0)

使用PIL /枕头来做到这一点:

materiale_value*2+1

示例输出

#!/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')       

Move-Item