简体   繁体   中英

How to slice a certain portion of an image in python?

I have an input image that has a mouth photo in a dark background: input image

I want only the mouth portion as output: output image

Use https://scikit-image.org/ library. You can crop it as easy as below.

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

Try this 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)

Output:

在此处输入图像描述

Like this with 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')       

Sample Output

(70, 155, 182, 223)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM