【发布时间】:2021-03-02 04:32:59
【问题描述】:
我目前正在研究以下内容,并且正在努力了解最佳方法。 我进行了很多搜索,但找不到与我正在尝试做的事情相匹配的答案
问题:
- 将现有图像(白色背景)中的对象(例如鞋子)重新定位到特定位置(例如向上移动)
- 在用户指定的新背景(仍为白色)内的用户指定位置插入和定位对象(例如鞋),并由用户指定新的高度/宽度
我走了多远:
我已经设法使用 CV2 识别图片中的对象,获取外部轮廓,添加一点填充并裁剪对象(见下文)。我很高兴以这种方式裁剪它,因为我的所有图像都有一个单一颜色的背景,并且我将保持背景颜色相同。
我被困在哪里: 我裁剪的对象和旧图像背景/新背景不共享相同的形状,因此我无法覆盖/连接/合并... 鉴于这两个图像都存储为 np 数组,我假设答案是以某种方式将 Shoe crop np.array 放在背景 np.array 中,但是我不知道如何做到这一点。 也许有更简单/不同的方法来做到这一点?
非常感谢任何能引导我走向正确方向的人的来信。
代码
#importing dependencies
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
# Config
path = '/Users/..../Shoes/'
img_list = os.listdir(path)
img_path = path + img_list[0]
#Outline
color = (0,255,0)
thickness = 3
padding = 10
# convert to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# create a binary thresholded image
_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)
# find the contours from the thresholded image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Identifying outer contours
x_axis = []
y_axis = []
for i in range(len(contours)):
for y in range (len(contours[i])):
x_axis.append(contours[i][y][0][0])
y_axis.append(contours[i][y][0][1])
min_x = min(x_axis) - padding
min_y = min(y_axis) - padding
max_x = max(x_axis) + padding
max_y = max(y_axis) + padding
# Defining start and endpoint of outline Rectangle based on identified outer corners + Padding
start_point = (min_x, min_y)
end_point = (max_x, max_y)
image_outline = cv2.rectangle(image, start_point, end_point, color, thickness)
plt.imshow(image_outline)
plt.show()
#Crop Image
crop_img = image[min_y:max_y, min_x:max_x]
print(crop_img.shape)
plt.imshow(crop_img)
plt.show()
【问题讨论】:
-
您要从原始图像中截取鞋子的裁剪图像并将其放在新图像的中心(具有相同背景)吗?
标签: python numpy image-processing cv2