How to resize an image with OpenCV2.0 and Python2.6

后端 未结 5 1868
暗喜
暗喜 2020-11-27 10:26

I want to use OpenCV2.0 and Python2.6 to show resized images. I used and adopted this example but unfortunately, this code is for OpenCV2.1 and does not seem to be working o

5条回答
  •  囚心锁ツ
    2020-11-27 11:12

    Example doubling the image size

    There are two ways to resize an image. The new size can be specified:

    1. Manually;

      height, width = src.shape[:2]

      dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

    2. By a scaling factor.

      dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), where fx is the scaling factor along the horizontal axis and fy along the vertical axis.

    To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).

    Example shrink image to fit a max height/width (keeping aspect ratio)

    import cv2
    
    img = cv2.imread('YOUR_PATH_TO_IMG')
    
    height, width = img.shape[:2]
    max_height = 300
    max_width = 300
    
    # only shrink if img is bigger than required
    if max_height < height or max_width < width:
        # get scaling factor
        scaling_factor = max_height / float(height)
        if max_width/float(width) < scaling_factor:
            scaling_factor = max_width / float(width)
        # resize image
        img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
    
    cv2.imshow("Shrinked image", img)
    key = cv2.waitKey()
    

    Using your code with cv2

    import cv2 as cv
    
    im = cv.imread(path)
    
    height, width = im.shape[:2]
    
    thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)
    
    cv.imshow('exampleshq', thumbnail)
    cv.waitKey(0)
    cv.destroyAllWindows()
    

提交回复
热议问题