本文整理汇总了Python中skimage.color.rgb2gray函数的典型用法代码示例。如果您正苦于以下问题:Python rgb2gray函数的具体用法?Python rgb2gray怎么用?Python rgb2gray使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rgb2gray函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_simple
def run_simple(self):
u'''Simple prediction'''
if len(self.datapath) >= 2:
# Use only two previous images
af_img = io.imread(self.datapath[0])
bf_img = io.imread(self.datapath[1])
#af_img = io.imread(r'./viptrafficof_02.png')
#bf_img = io.imread(r'./viptrafficof_03.png')
# Convert to gray image
af_gray = color.rgb2gray(af_img)
bf_gray = color.rgb2gray(bf_img)
# Calculate density flow
# Small -> WHY?
flow = cv2.calcOpticalFlowFarneback(bf_gray, af_gray, \
0.5, 6, 20, 10, 5, 1.2, 0)
print flow.shape, flow[:, :, 0].min(), flow[:, :, 1].max()
self.before = bf_gray
self.after = af_gray
#self.result = self.current
self.result = transform(af_img, flow)
# Color code the result for better visualization of optical flow.
# Direction corresponds to Hue value of the image.
# Magnitude corresponds to Value plane
mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
hsv = np.zeros_like(af_img)
hsv[...,1] = 255
hsv[...,0] = ang*180/np.pi/2
hsv[...,2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
self.optical = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
示例2: motion_trajectories_stack_feature_image
def motion_trajectories_stack_feature_image(cap_stream,morp_stream):
kernel = np.ones((5,5),np.uint8) #kernal function for open operation
stack_feature = np.zeros((240,320),dtype=float);
frame_t1 = np.zeros((240,320),dtype=float)
start = 0;
if cap_stream.isOpened():
ret, frame = cap_stream.read()
morp_frame = cv2.morphologyEx(frame,cv2.MORPH_CLOSE,kernel) #remove outlier using open operation
morp_stream.write(morp_frame)
while(True):
frame_t1 = color.rgb2gray(morp_frame)
if ret==True:
#if a pixel have a different value to previous frame then it occur
ret, frame = cap_stream.read()
if ret==True:
morp_frame = cv2.morphologyEx(frame,cv2.MORPH_CLOSE,kernel) #remove outlier using open operation
morp_stream.write(morp_frame)
frame_t2 = color.rgb2gray(morp_frame)
stack_feature = stack_feature + (frame_t2-frame_t1)*0.1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
else:
break
return stack_feature
示例3: image_compare
def image_compare(df, IMAGES_DIR='/home/ryan/asi_images/'):
'''
takes a list of n image ids and returns sum(n..n-1) n comparisons of r2 difference, r2(fft) difference, and average number of thresholded pixels
'''
img_buffer = {}
return_list = []
artdf = df[['_id', 'images']].copy()
artdf.images = artdf.images.apply(getpath)
paths = artdf[['_id','images']].dropna()
paths.index = paths._id
paths = paths.images
if paths.shape[0] < 2:
return DataFrame([])
for id_pair in combinations(paths.index, 2):
if id_pair[0] in img_buffer:
img1 = img_buffer[id_pair[0]]
else:
img_buffer[id_pair[0]] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + paths[id_pair[0]]), (300,300))))
img1 = img_buffer[id_pair[0]]
if id_pair[1] in img_buffer:
img2 = img_buffer[id_pair[1]]
else:
img_buffer[id_pair[1]] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + paths[id_pair[1]]), (300,300))))
img2 = img_buffer[id_pair[1]]
return_list.append(
[id_pair[0], id_pair[1], \
norm(img1 - img2), \
norm(fft2(img1) - fft2(img2)), \
#mean([sum(img1 > threshold_otsu(img1)), sum(img2 > threshold_otsu(img2))])]
#mean([sum(img1 > 0.9), sum(img2 > 0.9)])]
std(img1)+std(img2)/2.]
)
return DataFrame(return_list, columns=['id1','id2','r2diff', 'fftdiff', 'stdavg'])
示例4: test
def test(classifier, pca):
building = io.imread("http://www.nps.gov/tps/images/briefs/14-commercial-building.jpg")
building = transform.resize(building, (200, 200, 3))
building = color.rgb2gray(building)
building = building.reshape(1, -1)
# building = pca.transform(building)
print building
print classifier.predict(building)[0]
print to_cat[str(classifier.predict(building)[0])] + " (expect building)"
# print classifier.predict_proba(building)
snow = io.imread("http://farm4.static.flickr.com/3405/3332148397_92d89db2ab.jpg")
snow = transform.resize(snow, (200, 200, 3))
snow = color.rgb2gray(snow)
snow = snow.reshape(1, -1)
# snow = pca.transform(snow)
print snow
print to_cat[str(classifier.predict(snow)[0])] + " (expect snow)"
# print classifier.predict_proba(snow)
flower = io.imread("https://upload.wikimedia.org/wikipedia/commons/f/fd/Daisy_flower_green_background.jpg")
flower = transform.resize(flower, (200, 200, 3))
flower = color.rgb2gray(flower)
flower = flower.reshape(1, -1)
# flower = pca.transform(flower)
print to_cat[str(classifier.predict(flower)[0])] + " (expect plant)"
示例5: iris_scan_orb_android
def iris_scan_orb_android(file_name):
from skimage import io
from skimage.feature import (match_descriptors, ORB)
from skimage.color import rgb2gray
from .settings import MEDIA_ROOT
img1 = rgb2gray(io.imread(MEDIA_ROOT + '/'+ file_name)) # Query
img2 = rgb2gray(io.imread(MEDIA_ROOT + '/IRIS9.jpg')) # Comparing to
descriptor_extractor = ORB(n_keypoints=200)
descriptor_extractor.detect_and_extract(img1)
keypoints1 = descriptor_extractor.keypoints
descriptors1 = descriptor_extractor.descriptors # Query Descriptor
descriptor_extractor.detect_and_extract(img2)
keypoints2 = descriptor_extractor.keypoints
descriptors2 = descriptor_extractor.descriptors # Comparing To Descriptors
matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)
percent = len(matches12) / len(descriptors1) * 100
return percent
示例6: repeated_sales
def repeated_sales(df, artistname, artname, r2thresh=7000, fftr2thresh=10000, IMAGES_DIR='/home/ryan/asi_images/'):
"""
Takes a dataframe, artistname and artname and tries to decide, via image matching, if there is a repeat sale. Returns a dict of lot_ids, each entry a list of repeat sales
"""
artdf = df[(df['artistID']==artistname) & (df['artTitle']==artname)]
artdf.images = artdf.images.apply(getpath)
paths = artdf[['_id','images']].dropna()
id_dict = {}
img_buffer = {}
already_ordered = []
for i, path_i in paths.values:
id_dict[i] = []
img_buffer[i] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + path_i), (300,300))))
for j, path_j in paths[paths._id != i].values:
if j > i and j not in already_ordered:
if j not in img_buffer.keys():
img_buffer[j] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + path_j), (300,300))))
if norm(img_buffer[i] - img_buffer[j]) < r2thresh and\
norm(fft2(img_buffer[i]) - fft2(img_buffer[j])) < fftr2thresh:
id_dict[i].append(j)
already_ordered.append(j)
for key in id_dict.keys():
if id_dict[key] == []:
id_dict.pop(key)
return id_dict
示例7: main
def main():
try:
if len(sys.argv) <= 1:
print 'Error: Filename Required'
if len(sys.argv) == 2:
print 'Error: Background Filename Required'
if len(sys.argv) >= 3:
# Constants
Window_Size = 5
image_name = sys.argv[1]
ref_name = sys.argv[2]
image = rgb2gray(io.imread(sys.argv[1]))
ref = rgb2gray(io.imread(sys.argv[2]))
part_image, region, angle = pre.interest_region(image, plot_image = 0)
ref_rotate = rotate(ref,angle)
part_ref = ref_rotate[region[0]:region[1], region[2]:region[3]]
pre_image = pre.noise_reduction(part_image, part_ref, Window_Size, mode = 0)
io.imsave('pre_image.jpg',pre_image)
except KeyboardInterrupt:
print "Shutdown requested... exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
示例8: process_images
def process_images(d, files, analysis_fxn):
'''
Opens images and starts the analysis_fxn
Inputs:
d, string, current cell folder
files, list of strings, names of the files in the
current cell folder
analysis_fxn, function, type of analysis to perform
Returns:
None
'''
nom = os.path.join(d, files[3]) #Nom_crop
mch = os.path.join(d, files[2])
nom_im = Image.open(nom)
gray_nom = color.rgb2gray(nom_im)
mch_im = Image.open(mch)
gray_mch = color.rgb2gray(gray_im)
analysis_fxn(gray_nom, gray_mch)
return None
示例9: count_bubble
def count_bubble(image_filename, ref_filename, plot_show = 0):
image = io.imread(gv.__DIR__ + gv.__TrainImageDir__ + \
image_filename)
ref_image = io.imread(gv.__DIR__ + gv.__TrainImageDir__ + \
ref_filename)
image_gray = rgb2gray(image)
ref_gray = rgb2gray(ref_image)
# Constants
Window_Size = 5
pre_image = pre.noise_reduction(image_gray,
ref_gray,
Window_Size,
mode = 0)
seg_image = segmentation(pre_image,'self_design')
perimeters = perimeter_exaction(seg_image, image, image_filename)
if(plot_show == 1):
fig, ax = plt.subplots(1,3)
ax[0].imshow(image)
ax[0].set_title('Original')
ax[1].imshow(seg_image, cmap=plt.cm.gray)
ax[1].set_title('Segmentation')
result = io.imread(gv.__DIR__ + gv.cu__image_dir + image_filename)
ax[2].imshow(result)
ax[2].set_title('Result')
plt.show()
return perimeters
示例10: iris_scan_orb
def iris_scan_orb(request):
from skimage import io
from skimage.feature import (match_descriptors, ORB)
from skimage.color import rgb2gray
from .settings import MEDIA_ROOT
img1 = rgb2gray(io.imread(MEDIA_ROOT + '/IRIS3.jpg')) # Query
img2 = rgb2gray(io.imread(MEDIA_ROOT + '/IRIS6.jpg')) # Comparing to
descriptor_extractor = ORB(n_keypoints=200)
descriptor_extractor.detect_and_extract(img1)
keypoints1 = descriptor_extractor.keypoints
descriptors1 = descriptor_extractor.descriptors # Query Descriptor
descriptor_extractor.detect_and_extract(img2)
keypoints2 = descriptor_extractor.keypoints
descriptors2 = descriptor_extractor.descriptors # Comparing To Descriptors
matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)
# print("Matched: ", len(matches12), " of ", len(descriptors1))
percent = len(matches12) / len(descriptors1) * 100
# print("Percent Match - ", percent, "%")
"""if percent > 80:
print("Matched!")
else:
print("Not Matched!")"""
return render(request, 'scan.html', {'percent': percent})
示例11: compare_images
def compare_images(imageA, imageB):
# compute the mean squared error and structural similarity
# index for the images
m = mse(imageA, imageB)
s = ssim(color.rgb2gray(imageA), color.rgb2gray(imageB))
if(m>500):print(m)
if(s<0.85): print(s)
示例12: image_similarity_index
def image_similarity_index(image_1_path_name, image_2_path_name):
"""Calculates the similarity of two images. A structural similarity index of 1.0 means the images are identical."""
image_1 = color.rgb2gray(imread(image_1_path_name)) # color-images are not supported in the version for Raspbian
image_2 = color.rgb2gray(imread(image_2_path_name))
similarity = compare_ssim(image_1, image_2)
return similarity
示例13: precisionRecall
def precisionRecall(self):
test_images = []
test_blobs = []
X = []
Y_ground = []
#Get blobs
for i in range(500,505):
file = self.croppedImages[i]
iter_image = rgb2gray(cv2.imread(file))
iter_blobs = blob_dog(iter_image, min_sigma=1, max_sigma=25,
sigma_ratio=1.6, threshold=.25, overlap=0.5)
test_images.append(iter_image)
test_blobs.append(iter_blobs)
print("Get blobs: " + str(i) + "/1000")
#Get X values for testing
for i in range(0, len(test_images)):
RadPic = self.RadPIC(10, test_blobs[i], rgb2gray(test_images[i]))
inputHOG = self.HOG(10, test_blobs[i], rgb2gray(test_images[i]))
X.extend(self.makeX(RadPic, inputHOG))
print("X: " + str(i) + "/1000")
#Get Y ground truth values
for i in range(500, 505):
j = i
tempStr = self.labels[j]
while tempStr.find("frame" + str(i)) == -1:
j = j + 1
tempStr = self.labels[j]
label_image = cv2.imread((glob.glob(tempStr))[0])
cropped_image = cv2.imread((glob.glob("cropped_images/frame" + str(i) + ".jpg"))[0])
cropped_image = rgb2gray(cropped_image)
blobs = blob_doh(cropped_image, min_sigma=1, max_sigma=25, num_sigma=15, threshold=.001)
for blob in blobs:
y, x, r = blob
if label_image[y,x][0] == 255 & label_image[y,x][1] == 255 & label_image[y,x][2] == 255:
Y_ground.append(1)
else:
Y_ground.append(0)
#print("Ground Truth: " + str(i) + "/1000")
#Open classifier
with open('croppedImagesV2.pkl', 'rb') as f:
forest = pickle.load(f)
#Precidicions
Y_classifier = forest.predict(X)
#Precision-Recall
precision, recall, thresholds = precision_recall_curve(Y_ground, Y_classifier)
plt.plot(recall, precision)
plt.ylabel('Precision')
plt.xlabel('Recall')
plt.show()
示例14: get_displacement
def get_displacement(image0, image1):
"""
Gets displacement (in pixels I think) difference between 2 images using scikit-image
not as accurate as the opencv version i think.
:param image0: reference image
:param image1: target image
:return:
"""
from skimage.feature import (match_descriptors, ORB, plot_matches)
from skimage.color import rgb2gray
from scipy.spatial.distance import hamming
from scipy import misc
image0_gray = rgb2gray(image0)
image1_gray = rgb2gray(image1)
descriptor_extractor = ORB(n_keypoints=200)
descriptor_extractor.detect_and_extract(image0_gray)
keypoints1 = descriptor_extractor.keypoints
descriptors1 = descriptor_extractor.descriptors
descriptor_extractor.detect_and_extract(image1_gray)
keypoints2 = descriptor_extractor.keypoints
descriptors2 = descriptor_extractor.descriptors
matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)
# Sort the matches based on distance. Least distance
# is better
distances12 = []
for match in matches12:
distance = hamming(descriptors1[match[0]], descriptors2[match[1]])
distances12.append(distance)
indices = np.arange(len(matches12))
indices = [index for (_, index) in sorted(zip(distances12, indices))]
matches12 = matches12[indices]
# collect displacement from the first 10 matches
dx_list = []
dy_list = []
for mat in matches12[:10]:
# Get the matching key points for each of the images
img1_idx = mat[0]
img2_idx = mat[1]
# x - columns
# y - rows
(x1, y1) = keypoints1[img1_idx]
(x2, y2) = keypoints2[img2_idx]
dx_list.append(abs(x1 - x2))
dy_list.append(abs(y1 - y2))
dx_median = np.median(np.asarray(dx_list, dtype=np.double))
dy_median = np.median(np.asarray(dy_list, dtype=np.double))
# plot_matches(image0, image1, descriptors1, descriptors2, matches12[:10])
return dx_median, dy_median
示例15: process
def process(self, img2, image_gray):
# img2 = warp(img2)
patch_size = [640]
img2 = rgb2gray(img2)
image_gray = rgb2gray(img2)
blobs_dog = blob_dog(image_gray, min_sigma=0.2, max_sigma=225, sigma_ratio=1.6, threshold=.5)
blobs_dog[:, 2] = blobs_dog[:, 2]
blobs = [blobs_dog]
colors = ['black']
titles = ['Difference of Gaussian']
sequence = zip(blobs, colors, titles)
# plt.imshow(img2)
# plt.axis("equal")
# plt.show()
for blobs, color, title in sequence:
print(len(blobs))
for blob in blobs:
y, x, r = blob
plotx = x
ploty = y
for i in range (3):
keypoints1 = corner_peaks(corner_harris(Array.image_arr[i]), min_distance=1)
keypoints2 = corner_peaks(corner_harris(img2), min_distance=1)
extractor = BRIEF(patch_size=30, mode="uniform")
extractor.extract(Array.image_arr[i], keypoints1)
keypoints1 = keypoints1[extractor.mask]
descriptors1 = extractor.descriptors
extractor.extract(img2, keypoints2)
keypoints2 = keypoints2[extractor.mask]
descriptors2 = extractor.descriptors
matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)
# print(keypoints1, keypoints2)
# print(matches12)
#FUCKGGGPLAYT
for pizdezh in matches12:
X = keypoints2[pizdezh[1]][1]
Y = keypoints2[pizdezh[1]][0]
if sqrt((plotx - X)**2 + (ploty - Y)**2) < r:
seen = [{
"type": Array.type_arr[i],
"center_shift": (plotx - 160/2) * -0.02,
"distance": image_gray[y][x] / 0.08
}]
print seen
data.seen.add(seen)
break