gpt4 book ai didi

python - 根据像素值裁剪 rgb 图像

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

我有一个 rgb 图像,我想从各个方面裁剪它。我已经在灰度图像上尝试了下面的代码,它可以工作,但对于 RGB 图像它没有。
我的代码是:

    import cv2 
import numpy as np
import glob,os
from PIL import Image

inputdir = "/Users/sripdeep/Desktop/Projects/3 Norm_Sub_Norm/rgb/"
outpath = "/Users/sripdeep/Desktop/Projects/3 Norm_Sub_Norm/rgb_norm/"

#filesname = sorted(glob.glob( inputdir + "*.jpg"))

for img1 in sorted(glob.glob( inputdir + "*.jpeg")):

img_path = img1.split('/')[-1]
imgstr = img_path.split('.')[0]

print(imgstr)
im1 = cv2.imread(img1,0)
thresh = cv2.threshold(im1, 100, 255, cv2.THRESH_BINARY)[1]
x, y, w, h = cv2.boundingRect(im1) # calculates nonzero pixels
# print(x,y,w,h)
# a tuple (x, y, w, h) with (x, y) the upper left point
# as well as width w and height h of the bounding rectangle.

left = (x, np.argmax(thresh[:, x])) #
right = (x+w-1, np.argmax(thresh[:, x+w-1])) #
top = (np.argmax(thresh[y, :]), y) #
bottom = (np.argmax(thresh[y+h-1, :]), y+h-1)

print('left: {}'.format(left))
print('right: {}'.format(right))
print('top: {}'.format(top))
print('bottom: {}'.format(bottom))

# cropped__img = img[y1:y2, x1:x2]
cropped__img = thresh[top[1]:bottom[1], left[0]:right[0]]
cropped__img = cv2.resize(cropped__img, (256,256), interpolation=cv2.INTER_LINEAR)

save_fname = os.path.join(outpath, os.path.basename(imgstr)+'.jpg')
cv2.imwrite(save_fname, cropped__img)
我希望像这样裁剪我的图像:
enter image description here
但我得到的输出是:
enter image description here

最佳答案

您的方法很接近,可以稍微简化一下。
请注意 cv2.boundingRect(..)只能应用于单 channel 图像。因此,首先读取彩色图像,然后将其转换为灰度以找出边界矩形 (x,h,w,h) 坐标 (x1, y1, x2, y2) 似乎最容易,然后将裁剪应用于原始彩色图像。
也许是这样的:

im1 = cv2.imread(img1,0) # color image
im1_gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) # grayscale
thresh = cv2.threshold(im1_gray, 100, 255, cv2.THRESH_BINARY)[1] # threshold image
x, y, w, h = cv2.boundingRect(thresh) # find the bounding rectangle of nonzero points in the image
cropped__img = im1[y:y+h, x:x+w,:] # crop the original color image

关于python - 根据像素值裁剪 rgb 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62566698/

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