我的目标是用矩形裁剪图像并以灰度保存裁剪,但我无法理解代码中的错误

My goal is to crop the image with a rectangle and save the crop in grayscale, but I can't understand the error in the code

import cv2

path = r'C:\Users\Dell\JB\ocrprints\house.png'

imagem = cv2.Imread(path, cv2.IMREAD_GRAYSCALE)

cv2.rectangle(imagem,(384,0),(510,128),(0,255,0),3)

cv2.imshow("Final", imagem)

cv2.imwrite("Final.png", imagem)    

cv2.waitKey(0)

给出这个错误

#Erro File "c:\Users\Dell\JB\ocrprints\captura.py", line 5, in imagem = cv2.Imread(path, cv2.IMREAD_GRAYSCALE) AttributeError: module 'cv2.cv2' has no attribute 'Imread'

您的代码中有错字。读取图片的函数是cv2.imread(小写i),检查图片是否读取成功也是一个好习惯:

# Load image:
img = cv.imread(path, cv2.IMREAD_GRAYSCALE)

# Check if image was loaded:
if img is None:
  print("Image not loaded.")

你也可以手动给值(x,y),(w,h)和crop

    import cv2 
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    image=cv2.imread("ronaldo.jpg")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
         cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) 
         roi_image = gray[y:y+h, x:x+w]
    cv2.imshow("crop/region of interset image",roi_image) 
    cv2.waitKey(0)
    cv2.destroyAllWindows()