如何在 Python 中使用 OpenCV 对图像进行像素化?
How to pixelate image using OpenCV in Python?
此 link How to pixelate a square image to 256 big pixels with python? 中的最佳答案使用 PIL
对图像进行像素化。将图像从 PIL
转换为 cv2.Mat
是可能的,但我不允许使用其他库,而且我找不到任何使用 opencv 的好方法。
有没有什么方法可以仅在 Python 中使用 OpenCV
库对图像进行像素化?任何示例图像都可以。非常感谢我可以控制以供以后调整的像素大小参数的解决方案。
编辑^2
在他自己的帮助下,我移动了 Mark Setchell's answer, which is the above mentioned top answer, to plain OpenCV
Python code. (Have a look at the revision history 的答案以使用循环查看旧版本。)
import cv2
# Input image
input = cv2.imread('images/paddington.png')
# Get input size
height, width = input.shape[:2]
# 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)
输入(来自链接问题):
输出:
免责声明:一般来说,我是 Python 的新手,特别是 OpenCV 的 Python API(C++ 为赢)。非常欢迎提出意见、改进和强调 Python 不可行的问题!
此 link How to pixelate a square image to 256 big pixels with python? 中的最佳答案使用 PIL
对图像进行像素化。将图像从 PIL
转换为 cv2.Mat
是可能的,但我不允许使用其他库,而且我找不到任何使用 opencv 的好方法。
有没有什么方法可以仅在 Python 中使用 OpenCV
库对图像进行像素化?任何示例图像都可以。非常感谢我可以控制以供以后调整的像素大小参数的解决方案。
编辑^2
在他自己的帮助下,我移动了 Mark Setchell's answer, which is the above mentioned top answer, to plain OpenCV
Python code. (Have a look at the revision history 的答案以使用循环查看旧版本。)
import cv2
# Input image
input = cv2.imread('images/paddington.png')
# Get input size
height, width = input.shape[:2]
# 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)
输入(来自链接问题):
输出:
免责声明:一般来说,我是 Python 的新手,特别是 OpenCV 的 Python API(C++ 为赢)。非常欢迎提出意见、改进和强调 Python 不可行的问题!