Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an image but keep pixel's value with python

I'm dealing with some images, and I'd like to resize them from 1080 * 1920 to 480 * 640. I have classified every single pixel into a specific class so each of them has a unique value. However, those value of pixel would changed if I resized image.

python
resized = cv2.resize(image, (640, 480), interpolation = cv2.INTER_AREA)
print(set(resized.flat)) --> a dict {0,1,2,3,4……,38,39,40}
print(set(image.flat)) --> a dict {0,10,40}

# image size is 1080 * 1920
# resized size is 480 * 640

desired_image = cv2.imread(desired_image_path,cv2.IMREAD_GRAYSCALE).astype(np.uint8)
print(set(desired_image.flat)) --> a dict {0,10,40}

# desired_image size is 480 * 640

I expect to have the desired image which have the size of 480 * 640 without any crop and keep the pixel's value same. Now I have the correct size but value of pixels change a lot.

like image 834
Eunice TT Avatar asked Sep 02 '25 15:09

Eunice TT


1 Answers

If i understand you correctly, you want to resize the image without creating new pixel values. This can be done by setting the interpolation parameter of cv2.resize to INTER_NEAREST

resized = cv2.resize(image, (640, 480), interpolation = cv2.INTER_NEAREST)

Source: https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html#resize

like image 90
Saritus Avatar answered Sep 05 '25 19:09

Saritus