无法使用 img.shape 中的高度和宽度进行进一步计算

Cannot use height and width from img.shape for further calculations

我正在尝试使用 cv2 将图像分割成多个块。我的问题是 cv2.imread,识别我的高度和宽度,但是当我使用这些值计算 x 和 y 时,我的结果是 0。

当我 运行 代码

时,我也会收到此错误

“slice indices must be integers or None or have an index method” on this part of the code img = img[y:y+h, x:x+w]"

 import cv2
 import time

 img = cv2.imread('C:/Users/ML/Desktop/DataMatrix/Unbenannt.png')
 img2 = img

 height, width, channels = img.shape

 print (height, width, channels)
 CROP_W_SIZE  = 2 
 CROP_H_SIZE = 2

 for ih in range(CROP_H_SIZE ):
     for iw in range(CROP_W_SIZE ):

        x = width / CROP_W_SIZE * iw
        y = height / CROP_H_SIZE * ih
        h = (height / CROP_H_SIZE)
        w = (width / CROP_W_SIZE )

        print(x,y,h,w)

        img = img[y:y+h, x:x+w]

        NAME = str(time.time()) 
        cv2.imwrite("C:/Users/ML/Desktop/DataMatrix/CROP/" + str(time.time()) +  ".png",img)
        img = img2

您只需围绕 x、y、w、h 的计算添加一个 int() 函数。当你除法时,它们会被转换成浮点数。

  • x 和 y 的值似乎为 0,因为在循环的第一次迭代中,ih 和 iw 的值为 0。

  • 索引错误是因为在Python3中,除法不是整数除法而是returns一个浮点数。您可能想改用 //。