I have a 16bit grayscale image and I want to convert it to a 8bit grayscale image in OpenCV for python to use it with various functions (like findContours etc.). Is it possible to do it in python or I have to switch to C++?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
由 翻译强力驱动
问题:
回答1:
You can use numpy conversion methods as an OpenCV mat is a numpy array.
This works:
img8 = (img16/256).astype('uint8')
回答2:
You can do this in Python using NumPy by mapping the image trough a lookup table.
import numpy as np def map_uint16_to_uint8(img, lower_bound=None, upper_bound=None): ''' Map a 16-bit image trough a lookup table to convert it to 8-bit. Parameters ---------- img: numpy.ndarray[np.uint16] image that should be mapped lower_bound: int, optional lower bound of the range that should be mapped to ``[0, 255]``, value must be in the range ``[0, 65535]`` and smaller than `upper_bound` (defaults to ``numpy.min(img)``) upper_bound: int, optional upper bound of the range that should be mapped to ``[0, 255]``, value must be in the range ``[0, 65535]`` and larger than `lower_bound` (defaults to ``numpy.max(img)``) Returns ------- numpy.ndarray[uint8] ''' if not(0 <= lower_bound < 2**16) and lower_bound is not None: raise ValueError( '"lower_bound" must be in the range [0, 65535]') if not(0 <= upper_bound < 2**16) and upper_bound is not None: raise ValueError( '"upper_bound" must be in the range [0, 65535]') if lower_bound is None: lower_bound = np.min(img) if upper_bound is None: upper_bound = np.max(img) if lower_bound >= upper_bound: raise ValueError( '"lower_bound" must be smaller than "upper_bound"') lut = np.concatenate([ np.zeros(lower_bound, dtype=np.uint16), np.linspace(0, 255, upper_bound - lower_bound).astype(np.uint16), np.ones(2**16 - upper_bound, dtype=np.uint16) * 255 ]) return lut[img].astype(np.uint8) # Let's generate an example image (normally you would load the 16-bit image: cv2.imread(filename, cv2.IMREAD_UNCHANGED)) img = (np.random.random((100, 100)) * 2**16).astype(np.uint16) # Convert it to 8-bit map_uint16_to_uint8(img)
回答3:
For converting from 16 bit to 8 bit using python openCV:
import numpy as np import cv2 imagePath = "--" img_8bit = cv2.imread(imagePath).astype(np.uint8)