Saving and Reading Binary Image

Question:

Hello I want to save image after threshold:

binary=cv2.threshold(fark, 30, 255, cv2.THRESH_BINARY)[1]
binary.astype(np.uint8)
print binary.shape
cv2.imwrite("path"+str(counter)+".png",binary)

binary.shape output is: (320,240) —> This is what I want

But when i read the image:

image=cv2.imread(path)
print image.shape

output is (320,240,3) , and when i check out the array it has values like 254,253

What can i do for this stuation and what is the best file format to save binary image?

Asked By: minoset

||

Answers:

The threshed is already np.uint8, no change is needed.

th, threshed = cv2.threshold(fark, 30, 255, cv2.THRESH_BINARY)
print(threshed.dtype, threshed.shape)

But when use cv2.imread, default convert to BGR channels. To keep original shape and channels(for grayscale or png with alpha channel):

img = cv2.imread("test.png", cv2.IMREAD_UNCHANGED)

Or just for gray:

img = cv2.imread("test.png", cv2.IMREAD_GRAYSCALE)
Answered By: Kinght 金
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.