亲!马上注册或者登录会查看更多内容!
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
Coding up a Color Selection Let’s code upa simple color selection in Python. No need todownload or install anything, you can just follow along in the browser for now. We'll be working with the same imageyou saw previously.
Check out the code below. First, Iimport pyplot and image from matplotlib. I also import numpy for operating on the image. importmatplotlib.pyplot as plt importmatplotlib.image as mpimg import numpy as np I then readin an image and print out some stats. I’ll grab the x and y sizes and make acopy of the image to work with. NOTE: Always make a copy of arrays or othervariables in Python. If instead, you say "a = b" then all changes youmake to "a" will be reflected in "b" as well! 【i】# Read inthe image and print out some stats image =mpimg.imread('test.jpg') print('Thisimage is: ',type(image), 'withdimensions:',image.shape) 【i】# Grab thex and y size and make a copy of the image ysize =image.shape[0] xsize =image.shape[1] 【i】# Note:always make a copy rather than simply using "=" color_select= np.copy(image) Next I define a color threshold inthe variables red_threshold, green_threshold, and blue_thresholdand populate rgb_threshold with these values. This vectorcontains the minimum values for red, green, and blue (R,G,B) that I will allowin my selection. 【i】# Defineour color selection criteria 【i】# Note: ifyou run this code, you'll find these are not sensible values!! 【i】# Butyou'll get a chance to play with them soon in a quiz red_threshold= 0 green_threshold= 0 blue_threshold= 0 rgb_threshold= [red_threshold, green_threshold, blue_threshold] Next, I'llselect any pixels below the threshold and set them to zero. After that,all pixels that meet my color criterion will be retained, and those that do notwill be blacked out. 【i】# Identifypixels below the threshold thresholds= (image[:,:,0] | (image[:,:,1] | (image[:,:,2] color_select[thresholds]= [0,0,0] 【i】# Displaythe image plt.imshow(color_select) The result, color_select, is an image in which pixels that wereabove the threshold have been retained, and pixels below the threshold havebeen blacked out. In the code snippet above, red_threshold, green_threshold and blue_threshold are all set to 0, which implies all pixels will be included in the selection. In the next quiz, you will modify thevalues of red_threshold, green_threshold and blue_thresholduntil you retain as much of the lane linesas possible while dropping everything else. Your output image should look likethe one below.
Imageafter color selection


|