首页 > 解决方案 > OpenCV 重新调整图像大小然后应用过滤器

问题描述

我想修改下面的代码以调整图像大小然后阅读它。如果我这样做,我会收到一条错误消息。

sample = cv2.imread(sample)
TypeError: bad argument type for built-in operation 

谁能建议我需要做什么才能使此代码正常工作:

def __getitem__(self, idx):
    path = self.files[idx]
    sample = Image.open(path)
    sample = sample.resize((512, 512))
    sample = cv2.imread(path)
  
    # set blue and green channels to 0

    sample[:, :, 0] = 0
    sample[:, :, 1] = 0

标签: pythonopencv

解决方案


首先,确保正确设置路径。

例如:我想要我的目录中的所有.png图像。

  • 我会使用/*.png标签从目录中获取所有png。
from glob import glob

image_files = glob("/Users/ahmettavli/Pictures/*png")

其次,您首先阅读图像,然后调整它的大小。

from cv2 import imread
from cv2 import resize

img = imread(filename=path)
img = resize(src=img, dsize=(512, 512))

这是示例:

from glob import glob
from cv2 import imread
from cv2 import resize


class ReadImages:
    def __init__(self, files):
        self.files = files

    def __getitem__(self, idx):
        path = self.files[idx]
        img = imread(filename=path)
        img = resize(src=img, dsize=(512, 512))


if __name__ == '__main__':
    image_files = glob("/Users/ahmettavli/Pictures/*png")
    image_object = ReadImages(files=image_files)
    image_object.__getitem__(idx=0)

输出:


推荐阅读