How to pixelate image using OpenCV in Python?

谁都会走 提交于 2020-02-02 04:20:07

问题


Top answer in this link How to pixelate a square image to 256 big pixels with python? uses PIL to pixelate image. Converting image from PIL to cv2.Mat is possible but I'm not allowed to use other library, and I couldn't find any good method using opencv.

Is there any way to pixelate image using OpenCV library only in Python? Any sample image is fine. Solution with pixel size parameter that I can control for later adjustment would be very appreciated.


回答1:


EDIT^2

With the help of himself, I moved Mark Setchell's answer, which is the above mentioned top answer, to plain OpenCV Python code. (Have a look at the revision history of my answer to see the old version using a loop.)


import cv2

# Input image
input = cv2.imread('images/paddington.png')

# Get input size
width, height, _ = input.shape

# Desired "pixelated" size
w, h = (16, 16)

# Resize input to "pixelated" size
temp = cv2.resize(input, (w, h), interpolation=cv2.INTER_LINEAR)

# Initialize output image
output = cv2.resize(temp, (width, height), interpolation=cv2.INTER_NEAREST)

cv2.imshow('Input', input)
cv2.imshow('Output', output)

cv2.waitKey(0)

Input (from linked question):

Output:

Disclaimer: I'm new to Python in general, and specially to the Python API of OpenCV (C++ for the win). Comments, improvements, highlighting Python no-gos are highly welcome!



来源:https://stackoverflow.com/questions/55508615/how-to-pixelate-image-using-opencv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!