首页  编辑  

灰度图转伪色图,例如红外照片转伪色图

Tags: /Python/   Date Created:

方法一:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import cv2
import os
import sys, getopt
import matplotlib.pyplot as plt
import numpy as np

def help():
	print("转换红外图为彩色图 v1.0")
	print("用法: ir2color [-m 0~19] -i src -o dest")
	print("例如: ir2color -m 12 -i aaa.jpg -o aaa_result.jpg")
	sys.exit(0)

def main(argv):
	colors = [cv2.COLORMAP_AUTUMN, cv2.COLORMAP_BONE, cv2.COLORMAP_JET, 
				cv2.COLORMAP_WINTER, cv2.COLORMAP_RAINBOW, cv2.COLORMAP_OCEAN, 
				cv2.COLORMAP_SUMMER, cv2.COLORMAP_SPRING, cv2.COLORMAP_COOL, 
				cv2.COLORMAP_HSV, cv2.COLORMAP_PINK, cv2.COLORMAP_HOT, 
				cv2.COLORMAP_PARULA, cv2.COLORMAP_MAGMA, cv2.COLORMAP_INFERNO, 
				cv2.COLORMAP_PLASMA, cv2.COLORMAP_VIRIDIS, cv2.COLORMAP_CIVIDIS, 
				cv2.COLORMAP_TWILIGHT, cv2.COLORMAP_TWILIGHT_SHIFTED]
	src = ''
	dst = ''
	mode = cv2.COLORMAP_PLASMA
	if len(sys.argv) == 1:
		help()
		
	try:
		opts, args = getopt.getopt(argv, "hm:i:o:")
	except getopt.GetoptError:
		help()

	for opt, arg in opts:
		if opt == '-h':
			help()
			sys.exit()
		elif opt == '-i':
			src = arg
		elif opt == '-o':
			dst = arg
		elif opt == '-m':
			arg = int(arg)
			if arg < 0 or arg > 19:
				print("配色方案错误,必须为【0~19】")
				sys.exit(1)
			mode = colors[arg]
			
	if src == '' or dst == '':
		help()

	img = cv2.imread(src)
	img2 = cv2.applyColorMap(img, mode)
	cv2.imwrite(dst,img2)
	sys.exit(0)
	
if __name__ == "__main__":
   main(sys.argv[1:])

方法二:

import cv2
import os
import pdb

img = cv2.imread('LR918VVR7RY4_500.jpg')
#cv2.imshow('image',img)
#pdb.set_trace()
ht = img.shape[0]
wd = img.shape[1]
for i in range(0,ht):
    for j in range(0,wd):
        B = img[i][j][0]
        G = img[i][j][1]
        R = img[i][j][2]
        if B <= 51:
            img[i][j][0] = 255
        elif B <= 102:
            img[i][j][0] = 255 - (B-51)*5
        elif B <= 153:
            img[i][j][0] = 0
        else : img[i][j][0] = 0

        if G <= 51:
            img[i][j][1] = G*5
        elif G <= 102:
            img[i][j][1] = 255
        elif G <= 153:
            img[i][j][1] = 255
        elif G <= 204:
            img[i][j][1] = 255 - int(128.0*(G-153.0)/51.0 + 0.5)
        else : img[i][j][1] = 127 - int(127.0*(G-204.0)/51.0 + 0.5)

        if R <= 51:
            img[i][j][2] = 0
        elif R <= 102:
            img[i][j][2] = 0
        elif R <= 153:
            img[i][j][2] = (R-102)*5
        elif G <= 204:
            img[i][j][2] = 255
        else : img[i][j][2] = 255
cv2.imwrite('LR918VVR7RY4_500.jpg.jpg',img)
ir2color.exe (500.5KB)