0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cv2.cvtColorにIMREAD.GRAYSCALEを入れると4chで出力される

Last updated at Posted at 2024-04-08

ハマったので記録

事象

cv2.imreadでIMREAD_GRAYSCALEを入れていた影響で
cv2.cvtColorにIMREAD.GRAYSCALEを入れた時
この時出力結果が4chになる

期待値

画像のグレースケールを1chで返してくれるのが期待
[146 146 146 ... 147 148 149]

結果

[146 152 135 255]
[146 152 135 255]
[147 152 136 255]
...
[149 150 142 255]
[150 151 143 255]
なぜ?

解決策

cv2.cvtcolorにはcv2.COLOR_BGR2GRAYを入れる

import cv2 as cv
import os
import csv

cd = os.path.dirname(__file__)
ratio = 2

#read img
file_path = os.path.join(cd, "sample1.png")
img = cv.imread(file_path) #3ch

if img is None:
    print("Read error")

#get img size [height:width:color_bitdepth]
# print(img.shape)
height = img.shape[0]
width = img.shape[1]
#Enlargement
resize_img = cv.resize(img, (int(width*ratio), int(height*ratio)))

#cvtColor (image, code[, dst[, dstCn]])
#convert BGR to GREY

#By convertin grayscale, get only brightness value
gray_img = cv.cvtColor(resize_img, cv.COLOR_BGR2GRAY)
#ここの出力結果です
 print(gray_img)

# cv.imshow('window', gray_img)
# cv.waitKey(10)
  
def csv_out():
    with open('IMREAD_GRAYSCALE_2.csv', 'w', newline = '' ) as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(gray_img)
    # print(rgb_img)
csv_out()

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?