如何旋转图像以获得非空像素?

Ber*_*nik 2 python numpy image-processing

在下面链接的图像中,我需要获取此旋转矩形中的所有黄色/绿色像素并去除蓝色背景,以便矩形的轴与 x 轴和 y 轴对齐。

我正在使用 numpy 但不知道我应该做什么。

我将阵列上传到此驱动器中,以防有人想要使用实际的阵列

原始图像打印

我在这里先向您的帮助表示感谢。

小智 6

我使用与 user2640045 相同的图像,但方法不同。

import numpy as np
import cv2

# load and convert image to grayscale
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# binarize image
threshold, binarized_img = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# find the largest contour
contours, hierarchy = cv2.findContours(binarized_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key = cv2.contourArea)

# get size of the rotated rectangle
center, size, angle = cv2.minAreaRect(c)

# get size of the image
h, w, *_ = img.shape

# create a rotation matrix and rotate the image
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_img = cv2.warpAffine(img, M, (w, h))

# crop the image
pad_x = int((w - size[0]) / 2)
pad_y = int((h - size[1]) / 2)

cropped_img = rotated_img[pad_y : pad_y + int(size[1]), pad_x : pad_x + int(size[0]), :]
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述