K
K
kate2020-12-19 00:20:16
Python
kate, 2020-12-19 00:20:16

How to rewrite the cv2.resize() function?

Task: Reduce image size by 2 times
There is a function: resized = cv2.resize(img, dim, interpolation=cv2.INTER_CUBIC)
which uses bicubic interpolation.
They asked me to rewrite the assignment by hand.
That is, it is necessary to thin out the image by calculating the value of the thinned image as the arithmetic mean of four adjacent elements of the original image.
The cv2 library function works in the same way, but I have no idea how to rewrite it myself..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Dugin, 2020-12-19
@adugin

img = np.float32(img)
img = img[0::2, :] + img[1::2, :]
img = img[:, 0::2] + img[:, 1::2]
img = np.uint8(img / 4)

img = np.uint8(
    (np.float32(img[0::2, 0::2]) + img[0::2, 1::2] + img[1::2, 0::2] + img[1::2, 1::2]) / 4
)

kernel = np.ones((2, 2), dtype=np.float32) / 4
img = cv2.filter2D(img, cv2.CV_8U, kernel, anchor=(0, 0))[::2, ::2]

img = np.lib.stride_tricks.as_strided(
    img, (*np.array(img.shape[:2]) // 2, 4, 3), (*np.array(img.strides[:2]) * 2, *img.strides[1:])
).mean(axis=-2).astype(np.uint8)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question