gpt4 book ai didi

python - 如何在 Python 中从图片的其余部分剪切绿色背景和前景?

转载 作者:行者123 更新时间:2023-12-02 16:46:27 25 4
gpt4 key购买 nike

我正在尝试用绿色背景剪切多个图像。图片的中心是绿色的,我想从图片中剪掉其余部分。问题是,我从视频中获取图片,所以有时绿色中心更大,有时更小。我真正的任务是在结上使用 K-Means,因此我有例如绿色背景和两根绳子,一根蓝色和一根红色。

我将 python 与 opencv、numpy 和 matplotlib 一起使用。

我已经切了中心,但有时我切得太多,有时我切得太少。在此示例中,我的图像大小为 1920 x 1080。

Here the knot is left and there is more to cut

Here the knot is in the center

Here is another example

Here is my desired output from picture 1

Example 1 which doesn't work with all algorithm

Example 2 which doesn't work with all algorithm

Example 3 which doesn't work with all algorithm

到目前为止,这是我的代码:

import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image, ImageEnhance

img = cv2.imread('path')

print(img.shape)

imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

crop_img = imgRGB[500:500+700, 300:300+500]

plt.imshow(crop_img)
plt.show()

最佳答案

您可以将颜色更改为 hsv。

src = cv2.imread('path')
imgRGB = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
imgHSV = cv2.cvtColor(imgRGB, cv2.COLOR_BGR2HSV)

然后使用 inRange 仅查找绿色值。
lower = np.array([20, 0, 0])    #Lower values of HSV range; Green have Hue value equal 120, but in opencv Hue range is smaler [0-180]
upper = np.array([100, 255, 255]) #Uppervalues of HSV range
imgRange = cv2.inRange(imgHSV, lower, upper)

然后在非绿线之后使用形态学操作来填补空洞
#kernels for morphology operations
kernel_noise = np.ones((3,3),np.uint8) #to delete small noises
kernel_dilate = np.ones((30,30),np.uint8) #bigger kernel to fill holes after ropes
kernel_erode = np.ones((38,38),np.uint8) #bigger kernel to delete pixels on edge that was add after dilate function

imgErode = cv2.erode(imgRange, kernel_noise, 1)
imgDilate = cv2.dilate(imgErode , kernel_dilate, 1)
imgErode = cv2.erode(imgDilate, kernel_erode, 1)

将蒙版放在结果图像上。您现在可以轻松找到绿屏的角落( findContours 函数)或在后续步骤中使用结果图像
res = cv2.bitwise_and(imgRGB, imgRGB, mask = imgErode)  #put mask with green screen on src image

关于python - 如何在 Python 中从图片的其余部分剪切绿色背景和前景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54216736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com