用 python 裁剪手机图像
Posted
技术标签:
【中文标题】用 python 裁剪手机图像【英文标题】:Crop cellphone image with python 【发布时间】:2021-06-02 11:07:06 【问题描述】:我正在尝试裁剪文件夹中包含的所有图像。 我想将对象保留在图片中,并通过处理裁剪的图像并将其粘贴到与从源获得的坐标相同的另一个文件中来使背景变黑。
我将所有坐标存储在具有这种结构的 csv 文件中:
Filename | xmax | xmin | ymax | ymin |
---|---|---|---|---|
a.jpg | 768 | 4 | 512 | 8 |
b.jpg | 1200 | 3 | 899 | 10 |
我使用此代码来实现我的目标:
import cv2
import numpy as np
save_path = '/content/drive/MyDrive/Colab Notebooks/object_cropped'
train_path = '/content/train'
with open('min_max.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
xmax = int(row['xmax'])
xmin= int(row['xmin'])
ymax = int(row['ymax'])
ymin = int(row['ymin'])
image = cv2.imread(os.path.join(train_path , row['Filename']))
object_ = image[ymin:xmax, xmin:ymax]
h, w, c = image.shape
black_background = np.zeros([h, w, 3])
for y in range(h):
for x in range(w):
black_background[y,x] = [0,0,0]
black_background[ymin:xmax, xmin:ymax] = object_
cv2.imwrite(os.path.join(save_path , 'cropped_' + row['Filename']), black_background)
它对于从网络上拍摄的图像非常有效,但是当我尝试将此代码应用于手机拍摄的照片时,它不起作用。
两个图像(网络图像和手机图像)都是 jpg,水平和垂直分辨率:96dpi 位深度:24,唯一不同的是图像大小。
我该如何解决这个问题?
编辑: 示例:
照片:
我需要裁剪边界框内的对象。
但是当我应用代码时,结果是:
使用的值:
xmax = 949
xmin= 489
ymax = 1829
ymin = 181
这种情况只发生在使用手机或平板电脑拍摄的照片上。
【问题讨论】:
“它不起作用”到底涵盖了什么? Btw 对象是 Python 中的全局变量,你不应该覆盖它。 请发布您的实际输入图像和生成的输出图像。 我用更多细节编辑了我的问题。 【参考方案1】:问题是 object_ = image[ymin:xmax, xmin:ymax]。解决办法是:
import cv2
import numpy as np
save_path = '/content/drive/MyDrive/Colab Notebooks/object_cropped'
train_path = '/content/train'
with open('min_max.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
xmax = int(row['xmax'])
xmin= int(row['xmin'])
ymax = int(row['ymax'])
ymin = int(row['ymin'])
image = cv2.imread(os.path.join(train_path , row['Filename']))
object_ = image[ymin:ymax, xmin:xmax] ####the right solution
h, w, c = image.shape
black_background = np.zeros([h, w, 3])
for y in range(h):
for x in range(w):
black_background[y,x] = [0,0,0]
black_background[ymin:ymax, xmin:xmax] = object_ ####the right solution
cv2.imwrite(os.path.join(save_path , 'cropped_' + row['Filename']), black_background)
【讨论】:
以上是关于用 python 裁剪手机图像的主要内容,如果未能解决你的问题,请参考以下文章
Python and OpenCV - 为啥用 OpenCV 处理的裁剪图像仍然可以影响原始图像?
opencv-python:如何用边界框坐标裁剪图像[重复]