当前位置: 首页>>代码示例>>Python>>正文


Python image.imread方法代码示例

本文整理汇总了Python中matplotlib.image.imread方法的典型用法代码示例。如果您正苦于以下问题:Python image.imread方法的具体用法?Python image.imread怎么用?Python image.imread使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.image的用法示例。


在下文中一共展示了image.imread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: undistort_images

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def undistort_images(src, dst):
	"""
	undistort the images in src folder to dst folder
	"""
	# load dst, mtx
	pickle_file = open("../camera_cal/camera_cal.p", "rb")
	dist_pickle = pickle.load(pickle_file)
	mtx = dist_pickle["mtx"]  
	dist = dist_pickle["dist"]
	pickle_file.close()
	
	# loop the image folder
	image_files = glob.glob(src+"*.jpg")
	for idx, file in enumerate(image_files):
		print(file)
		img = mpimg.imread(file)
		image_dist = cv2.undistort(img, mtx, dist, None, mtx)
		file_name = file.split("\\")[-1]
		print(file_name)
		out_image = dst+file_name
		print(out_image)
		image_dist = cv2.cvtColor(image_dist, cv2.COLOR_RGB2BGR)
		cv2.imwrite(out_image, image_dist) 
开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:25,代码来源:helpers.py

示例2: wrap_images

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def wrap_images(src, dst):
	"""
	apply the wrap to images
	"""
	# load M, Minv
	img_size = (1280, 720)
	pickle_file = open("../helper/trans_pickle.p", "rb")
	trans_pickle = pickle.load(pickle_file)
	M = trans_pickle["M"]
	Minv = trans_pickle["Minv"]
	# loop the file folder
	image_files = glob.glob(src+"*.jpg")
	for idx, file in enumerate(image_files):
		print(file)
		img = mpimg.imread(file)
		image_wraped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)
		file_name = file.split("\\")[-1]
		print(file_name)
		out_image = dst+file_name
		print(out_image)
		# no need to covert RGB to BGR since 3 channel is same
		image_wraped = cv2.cvtColor(image_wraped, cv2.COLOR_RGB2BGR)
		cv2.imwrite(out_image, image_wraped) 
开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:25,代码来源:helpers.py

示例3: test_color_grid_thresh_dynamic

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def test_color_grid_thresh_dynamic(src, dst, s_thresh, sx_thresh):
	"""
	apply the thresh to images in a src folder and output to dst foler
	"""
	image_files = glob.glob(src+"*.jpg")
	for idx, file in enumerate(image_files):
		print(file)
		img = mpimg.imread(file)
		image_threshed = color_grid_thresh_dynamic(img, s_thresh=s_thresh, sx_thresh=sx_thresh)
		file_name = file.split("\\")[-1]
		print(file_name)
		out_image = dst+file_name
		print(out_image)
		# convert  binary to RGB, *255, to visiual, 1 will not visual after write to file
		image_threshed = cv2.cvtColor(image_threshed*255, cv2.COLOR_GRAY2RGB)
		cv2.imwrite(out_image, image_threshed) 
开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:18,代码来源:image_process.py

示例4: test_yellow_grid_thresh_images

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def test_yellow_grid_thresh_images(src, dst, y_low=(10,50,0), y_high=(30,255,255), sx_thresh=(20, 100)):
	"""
	apply the thresh to images in a src folder and output to dst foler
	"""
	image_files = glob.glob(src+"*.jpg")
	for idx, file in enumerate(image_files):
		print(file)
		img = mpimg.imread(file)
		image_threshed = yellow_grid_thresh(img, y_low, y_high, sx_thresh)
		
		file_name = file.split("\\")[-1]
		print(file_name)
		out_image = dst+file_name
		print(out_image)
		# convert  binary to RGB, *255, to visiual, 1 will not visual after write to file
		image_threshed = cv2.cvtColor(image_threshed*255, cv2.COLOR_GRAY2RGB)
		cv2.imwrite(out_image, image_threshed) 
开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:19,代码来源:image_process.py

示例5: test_yellow_white_thresh_images

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def test_yellow_white_thresh_images(src, dst, y_low=(10,50,0), y_high=(30,255,255), w_low=(180,180,180), w_high=(255,255,255)):
	"""
	apply the thresh to images in a src folder and output to dst foler
	"""
	image_files = glob.glob(src+"*.jpg")
	for idx, file in enumerate(image_files):
		print(file)
		img = mpimg.imread(file)
		image_threshed = yellow_white_thresh(img, y_low, y_high, w_low, w_high)
		
		file_name = file.split("\\")[-1]
		print(file_name)
		out_image = dst+file_name
		print(out_image)
		# convert  binary to RGB, *255, to visiual, 1 will not visual after write to file
		image_threshed = cv2.cvtColor(image_threshed*255, cv2.COLOR_GRAY2RGB)
		
		# HSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
		# V = HSV[:,:,2]
		# brightness = np.mean(V)
		# info_str = "brightness is: {}".format(int(brightness))
		# cv2.putText(image_threshed, info_str, (50,700), cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,255),2)
		
		cv2.imwrite(out_image, image_threshed) 
开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:26,代码来源:image_process.py

示例6: test

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def test():
	pickle_file = open("trans_pickle.p", "rb")
	trans_pickle = pickle.load(pickle_file)
	M = trans_pickle["M"]  
	Minv = trans_pickle["Minv"]

	img_size = (1280, 720)

	image_files = glob.glob("../output_images/undistort/*.jpg")
	for idx, file in enumerate(image_files):
		print(file)
		img = mpimg.imread(file)
		warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)
		file_name = file.split("\\")[-1]
		print(file_name)
		out_image = "../output_images/perspect_trans/"+file_name
		print(out_image)
		# convert to opencv BGR format
		warped = cv2.cvtColor(warped, cv2.COLOR_RGB2BGR)
		cv2.imwrite(out_image, warped) 
开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:22,代码来源:view_perspective.py

示例7: __init__

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def __init__(self, savename, imagename):

        self.path=os.path.dirname(procedural_city_generation.__file__)
        try:
            with open(self.path+"/temp/"+savename+ "_heightmap.txt", 'r') as f:
                self.border=[eval(x) for x in f.read().split("_")[-2:] if x is not '']
        except IOError:
            print("Run the previous steps in procedural_city_generation first! If this message persists, run the \"clean\" command")
            return
        if imagename ==  "diffused":
            print("Using diffused version of population density image")
            with open(self.path+"/temp/"+savename+ "_densitymap.txt", 'r') as f:
                densityname=f.read()

            print("Population density image is being set up")
            self.img=self.setupimage(self.path+"/temp/"+densityname)
            print("Population density image setup is finished")
            return
        else:
            print("Looking for image in procedural_city_generation/inputs/buildingheight_pictures")
            import matplotlib.image as mpimg
            self.img=mpimg.imread(self.path +"/inputs/buildingheight_pictures/" + imagename)
            print("Image found") 
开发者ID:josauder,项目名称:procedural_city_generation,代码行数:25,代码来源:BuildingHeight.py

示例8: main

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def main():
    import matplotlib.pyplot as plt

    import matplotlib.image as mpimg
    import sys, os
    sys.path.append("../../..")
    import procedural_city_generation

    from procedural_city_generation.roadmap.config_functions.Watertools import Watertools
    import Image
    import numpy as np
    img=np.dot(mpimg.imread(os.getcwd() + "/resources/manybodies.png")[..., :3], [0.299, 0.587, 0.144])

    w=Watertools(img)
    plt.imshow(img, cmap="gray")
    plt.show()
    f=w.flood(0.95, np.array([80, 2]))
    plt.imshow(f, cmap="gray")
    plt.show() 
开发者ID:josauder,项目名称:procedural_city_generation,代码行数:21,代码来源:WatertoolsTest.py

示例9: get

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def get(self, idx, path=None):
        x = None
        for i in self.fs.find({'filename': idx}):
            x = i.read()
            fmt = i.fmt
        if x is None:
            raise ValueError(f'There is no id in db: {idx}')
        with open((path or '') + idx + '.' + fmt, 'wb') as f:
            f.write(x)
        print(f'Your file saved at {(path or "") + idx + "." + fmt}')
        if fmt == 'png':
            img = mpimg.imread((path or '') + idx + '.' + fmt)
            plt.figure(figsize=[15, 8])
            plt.imshow(img)
            plt.show()
            plt.close()
        elif fmt == 'html':
            html = x.decode()
            width = int(html.split('var width = ')[1].split(',')[0])
            height = int(html.split('height = ')[1].split(';')[0])
            display(IFrame((path or '') + idx + '.' + fmt, width=width + 200, height=height + 200))
        elif fmt == 'json':
            with open((path or '') + idx + '.' + fmt) as f:
                x = json.load(f)
            return x 
开发者ID:retentioneering,项目名称:retentioneering-tools,代码行数:27,代码来源:cloud_logger.py

示例10: test_imsave_color_alpha

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def test_imsave_color_alpha():
    # Test that imsave accept arrays with ndim=3 where the third dimension is
    # color and alpha without raising any exceptions, and that the data is
    # acceptably preserved through a save/read roundtrip.
    from numpy import random
    random.seed(1)
    data = random.rand(256, 128, 4)

    buff = io.BytesIO()
    plt.imsave(buff, data)

    buff.seek(0)
    arr_buf = plt.imread(buff)

    # Recreate the float -> uint8 -> float32 conversion of the data
    data = (255*data).astype('uint8').astype('float32')/255
    # Wherever alpha values were rounded down to 0, the rgb values all get set
    # to 0 during imsave (this is reasonable behaviour).
    # Recreate that here:
    for j in range(3):
        data[data[:, :, 3] == 0, j] = 1

    assert_array_equal(data, arr_buf) 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:25,代码来源:test_image.py

示例11: visualize

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def visualize(img_id):
  img_descriptor = coco.loadImgs(img_id)
  file_name = coco_data_folder + "val/" + img_descriptor[0]['file_name']

  fig, ax = plt.subplots(1)
  img = mpimg.imread(file_name)
  ax.imshow(img)

  gt_ann_ids = coco.getAnnIds(imgIds=[img_id])
  gt_anns = coco.loadAnns(gt_ann_ids)
  dets = detections_by_imgid[img_id]
  print("Image", img_id, "Dets", len(dets), "GT", len(gt_anns))

  for gt in gt_anns:
    draw_box(ax, gt['bbox'], 'r', gt['category_id'], 1.0)
  for det in dets:
    draw_box(ax, det['bbox'], 'b', det['category_id'], det['score'])

  plt.show() 
开发者ID:tobiasfshr,项目名称:MOTSFusion,代码行数:21,代码来源:visualize_coco_detections.py

示例12: graphviz_plot

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def graphviz_plot(graph, fname="tmp_dotgraph.dot", show=True):
    if os.path.exists(fname):
        print("WARNING: Overwriting existing file {} for new plots".format(fname))
    f = open(fname,'w')
    f.writelines('digraph G {\nnode [width=.3,height=.3,shape=octagon,style=filled,color=skyblue];\noverlap="false";\nrankdir="LR";\n')
    for i in graph:
        for j in graph[i]:
            s= '      '+ i
            s +=  ' -> ' +  j + ' [label="' + str(graph[i][j]) + '"]'
            s+=';\n'
            f.writelines(s)
    f.writelines('}')
    f.close()
    graphname = fname.split(".")[0] + ".png"
    pe(["dot", "-Tpng", fname, "-o", graphname])

    if show:
        plt.imshow(mpimg.imread(graphname))
        plt.show() 
开发者ID:kastnerkyle,项目名称:tools,代码行数:21,代码来源:graph_tools.py

示例13: create_thumbnail

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def create_thumbnail(infile, thumbfile,
                     width=300, height=300,
                     cx=0.5, cy=0.5, border=4):
    baseout, extout = op.splitext(thumbfile)

    im = image.imread(infile)
    rows, cols = im.shape[:2]
    x0 = int(cx * cols - .5 * width)
    y0 = int(cy * rows - .5 * height)
    xslice = slice(x0, x0 + width)
    yslice = slice(y0, y0 + height)
    thumb = im[yslice, xslice]
    thumb[:border, :, :3] = thumb[-border:, :, :3] = 0
    thumb[:, :border, :3] = thumb[:, -border:, :3] = 0

    dpi = 100
    fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi)

    ax = fig.add_axes([0, 0, 1, 1], aspect='auto',
                      frameon=False, xticks=[], yticks=[])
    ax.imshow(thumb, aspect='auto', resample=True,
              interpolation='bilinear')
    fig.savefig(thumbfile, dpi=dpi)
    return fig 
开发者ID:matplotlib,项目名称:mpl-probscale,代码行数:26,代码来源:plot_generator.py

示例14: __init__

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def __init__(self, fileName = None, label = None, Mat = None):
        if fileName != None:
            self.imgName = fileName
            self.img     = image.imread(fileName)

            if len(self.img.shape) == 3:
                self.img     = self.img[:,:, 1]

        else:
            assert Mat != None
            self.img     = Mat

        self.label   = label

        #self.stdImg  = Image._normalization(self.img)

        #self.iimg    = Image._integrateImg(self.stdImg)

        #self.vecImg  = self.iimg.transpose().flatten()

        self.vecImg = Image._integrateImg( Image._normalization(self.img)  ).transpose().flatten() 
开发者ID:jasonleaster,项目名称:FaceDetection,代码行数:23,代码来源:image.py

示例15: compute_statistics

# 需要导入模块: from matplotlib import image [as 别名]
# 或者: from matplotlib.image import imread [as 别名]
def compute_statistics(self, files):
        """Use welford's method to compute mean and variance of the given
        dataset.

        See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm."""

        assert len(files) > 1

        n = 0
        mean = np.zeros(3)
        M2 = np.zeros(3)
        for j, filename in enumerate(files):
            #TODO ensure the pixel values are 0..255
            im = np.reshape(mpimg.imread(filename) * 255, [-1, 3])
            for i in range(np.shape(im)[1]):
                n = n + 1
                delta = im[i] - mean
                mean += delta / n
                M2 += delta * (im[i] - mean)
            sys.stdout.write('\r>> Processed %.1f%%' % (
                float(j) / float(len(files)) * 100.0))
            sys.stdout.flush()
        var = M2 / (n - 1)
        stddev = np.sqrt(var)
        return np.float32(mean), np.float32(stddev) 
开发者ID:simonmeister,项目名称:UnFlow,代码行数:27,代码来源:data.py


注:本文中的matplotlib.image.imread方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。