【问题标题】:How to save image with background removal using python opencv如何使用python opencv保存带有背景去除的图像
【发布时间】:2021-11-07 04:35:37
【问题描述】:

我有原始图像Original image 预处理后我得到这样的图像Processed image 现在我想保存没有黑色背景的图像我该怎么做?

import cv2
from google.colab.patches import cv2_imshow
import numpy as np

def rotate_image(image, angle):
  image_center = tuple(np.array(image.shape[1::-1]) / 2)
  rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
  result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)
  return result

img = cv2.imread('/content/52a3b700031458331e469345aaf00f27.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mask = np.zeros((img.shape[0], img.shape[1]))
blur = cv2.GaussianBlur(gray, (5,5),0)
ret, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2_imshow(thresh)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
largest_countour = max(contours, key = cv2.contourArea)
binary_mask = cv2.drawContours(mask, [largest_countour], 0, 1, -1)
new_img = img * np.dstack((binary_mask, binary_mask, binary_mask))
minRect = cv2.minAreaRect(largest_countour)
rotate_angle = minRect[-1] if minRect[-1] < 0 else -minRect[-1]
new_img = rotate_image(new_img, rotate_angle)

cv2_imshow(new_img )

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: python opencv image-processing cv2 opencv-contour


【解决方案1】:

在 Python/OpenCV 中,对处理后的图像进行阈值处理。然后得到中心白色矩形的轮廓。从轮廓中,您可以得到边界框。从边界框中,您可以使用 Numpy 裁剪图像。

gray = cv2.cvtColor(new_img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
largest_countour = max(contours, key = cv2.contourArea)
x,y,w,h = cv2.boundingRect(largest_countour)
new_img_crop = new_img[y:y+h, x:x+w]

【讨论】:

  • 问题中已经存在边界矩形。它只是旋转的。不需要 cvtColor + threshold + findcontours 来重新发现它。
  • 确实是一个很好的解决方案,但是需要将角点的旋转从旋转到未旋转。我认为这个 OP 这样做可能比弄清楚如何旋转角点更容易。像往常一样,解决问题通常有多种方法
  • @fmw42 这个 OP 如何工作?喜欢旋转角点?
  • @Med FutureXAI 对不起,我不明白这个问题。 OP = 原始海报(就是你)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2021-07-27
  • 1970-01-01
相关资源
最近更新 更多