Python OpenCV crop and save images

Problem Description

Select a region from the picture, Entersave

1.jpg
Here Insert Picture Description

Code

# -*- coding: utf-8 -*-
# @Author  : XerCis
# @Time    : 2020/3/18 20:00
# @Function: 从图片中选出某一区域,Enter保存

import cv2

# 读取图片
img = '1.jpg'
img = cv2.imread(img)
cv2.imshow('original', img)

# 选择ROI
roi = cv2.selectROI(windowName="original", img=img, showCrosshair=True, fromCenter=False)
x, y, w, h = roi
print(roi)

# 显示ROI并保存图片
if roi != (0, 0, 0, 0):
    crop = img[y:y+h, x:x+w]
    cv2.imshow('crop', crop)
    cv2.imwrite('crop.jpg', crop)
    print('Saved!')

# 退出
cv2.waitKey(0)
cv2.destroyAllWindows()

PS: x, ycoordinates the ROI w, his the size of ROI

effect

Here Insert Picture Description
Percussion Enter
Here Insert Picture Description
get the picturecrop.jpg
Here Insert Picture Description

Remark

  1. OpenCV coordinate system origin in the upper left corner
Published 248 original articles · won praise 89 · views 160 000 +

Guess you like

Origin blog.csdn.net/lly1122334/article/details/104945976