def flippingOp(self): # read image im = cv2.imread(self.Image) # flip the image horizontally flipped = cv2.flip(im, 1) cv2.imshow("Flipped Horizontally", flipped) (b, g, r) = flipped[235, 259] print("red=%d, green=%d, blue=%d" % (r,g,b)) cv2.waitKey(0) # flip the image vertically flipped = cv2.flip(im, 0) cv2.imshow("Flipped Vertically", flipped) cv2.waitKey(0) # flip on both axis flipped = cv2.flip(im, -1) cv2.imshow("Flipped on both axis", flipped) cv2.waitKey(0) flipped = cv2.flip(im, 1) cv2.imshow("1", flipped) cv2.waitKey(0) rotated = imutils.rotate(flipped, 45) cv2.imshow("2", rotated) cv2.waitKey(0) flippedAgain = cv2.flip(rotated, 0) cv2.imshow("3", flippedAgain) cv2.waitKey(0) (b, g, r) = flippedAgain[189, 441] print("red=%d, green=%d, blue=%d" % (r,g,b)) return
def rotate_img(img, file_name, store_path, iter_count = 1): img_left_five = imutils.rotate(img, 3) img_left_five = cv2.resize(img_left_five, dim, interpolation=cv2.INTER_AREA) iter_count += 1 cv2.imwrite(join(store_path, file_name + '_' + str(iter_count)) + '.jpg', img_left_five) img_right_five = imutils.rotate(img, 358) img_right_five = cv2.resize(img_right_five, dim, interpolation=cv2.INTER_AREA) iter_count += 1 cv2.imwrite(join(store_path, file_name + '_' + str(iter_count) + '.jpg'), img_right_five) img_left_ten = imutils.rotate(img, 10) img_left_ten = cv2.resize(img_left_ten, dim, interpolation=cv2.INTER_AREA) iter_count += 1 cv2.imwrite(join(store_path, file_name + '_' + str(iter_count)) + '.jpg', img_left_ten) img_right_ten = imutils.rotate(img, 350) img_right_ten = cv2.resize(img_right_ten, dim, interpolation=cv2.INTER_AREA) iter_count += 1 cv2.imwrite(join(store_path, file_name + '_' + str(iter_count)) + '.jpg', img_right_ten)
def process_motion_frame(q, f, tick, ts, mfa=False, rotateAng=False, width=False, gBlur=(9, 9)): ''' This function defines the image processing techniques that are applied to a new thread when a frame is retreived from the camera. ''' rects_sal = [] fgmask = None f_copy = f.copy() if rotateAng is not False and rotateAng != 0: f = imutils.rotate(f, angle=rotateAng) if width is not False: f = imutils.resize(f, width=width) # blur & bg sub try: fgmask = fgbg.apply(cv2.GaussianBlur(f, gBlur, 0), learningRate=config.computing.learning_rate) except: print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) raise # get our frame outlines f_rects, rects_mot = get_motions(f, fgmask, thickness=1) rects_sal.extend(rects_mot) num_motion = len(rects_mot) if True: # don't do anything else if there's no motion of any kind detected # if num_motion > 0 or mfa is True: num_bodies = 0 num_faces = 0 if config.computing.body_detection_en or config.computing.face_detection_en: # generate a histogram equalized bw image if we're doing processing # that needs it f_bw = cv2.equalizeHist(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)) if config.computing.body_detection_en: fBody, rectsBody = detectPerson(f, color=(255, 0, 0)) if len(rectsBody) > 0: f_rects = cv2.add(f_rects, fBody) num_bodies = len(rectsBody) rects_sal.extend(rectsBody) if config.computing.face_detection_en: fFace, rectsFace = detectFace(f_bw, color=(0, 255, 0)) if len(rectsFace) > 0: f_rects = cv2.add(f_rects, fFace) num_faces = len(rectsFace) rects_sal.extend(rectsFace) f_rects = imutils.resize(f_rects, width=f_copy.shape[1]) q.put({"f": f_copy, "ts": ts, "rects_sal": rects_sal, "sz_scaled": getsize( f), "num_motion": num_motion, "num_bodies": num_bodies, "num_faces": num_faces}) return f_copy, f_rects, fgmask, rects_sal, tick, ts
def rotationOp(self): # read image im = cv2.imread(self.Image) # grab the dimension of the image (h, w) = im.shape[:2] (cX, cY) = (w/2, h/2) # rotate image by 45 degrees M = cv2.getRotationMatrix2D((cX, cY), 45, 1.0) rotated = cv2.warpAffine(im, M, (w,h)) cv2.imshow("Rotated by 45 degrees", rotated) cv2.waitKey(0) # rotate our image by -90 degrees M = cv2.getRotationMatrix2D((cX, cY), -90, 1.0) rotated = cv2.warpAffine(im, M, (w, h)) cv2.imshow("Rotated by -90 Degrees", rotated) cv2.waitKey(0) # using imutils rotated = imutils.rotate(im, 180) cv2.imshow("Rotated by 180 degrees using imutils", rotated) cv2.waitKey(0) rotated = imutils.rotate(im, -110) (b, g, r) = rotated[136, 312] print("red=%d, green=%d, blue=%d" % (r,g,b)) M = cv2.getRotationMatrix2D((50, 50), -88, 1.0) rotated = cv2.warpAffine(im, M, (w, h)) cv2.imshow("Rotated by -88 Degrees with offset (50,50)", rotated) (b, g, r) = rotated[10, 10] print("red=%d, green=%d, blue=%d" % (r,g,b)) cv2.waitKey(0) return
import argparse import cv2 import imutils as imu ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) print(image.shape) cv2.imshow("Original", image) (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, 45, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by 45 degrees", rotated) M = cv2.getRotationMatrix2D(center, -90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by -90 degrees", rotated) rotated = imu.rotate(image, 180) cv2.imshow("Rotated by 180 degrees", rotated) rotated = imu.rotate(image, 45) cv2.imshow("Rotated by 45 degrees, imutil", rotated) cv2.waitKey(0)
def getYlabel(img, xaxis): label_images = [] ylabels = [] ypixels = [] img = img[:,:max(0,xaxis['start']-5)] # Eliminate y title and tick marks img = axis_processing.eliminateYTitle(img) img = axis_processing.eliminateYTicks(img) # Obtain labels height, width = img.shape blur = cv2.GaussianBlur(img, (7,7), 0) thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,1)) dilate = cv2.dilate(thresh, kernel, iterations=4) cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] for c in cnts: x,y,w,h = cv2.boundingRect(c) # cv2.rectangle(img, (x, y), (x + w, y + h), 0, 2) ypixels.append(y+h//2) margin = 5 label_images.append(img[max(0,y-margin):min(height,y+h+margin), max(0,x-margin):min(width,x+w+margin)]) ylabels = [float('inf')]*len(ypixels) for i,lab in enumerate(label_images): lab = cv2.resize(lab, None, fx=10.5, fy=10.5, interpolation=cv2.INTER_CUBIC) kernel = np.ones((1, 1), np.uint8) lab = cv2.dilate(lab, kernel, iterations=4) _, lab = cv2.threshold(lab, 200, 255, cv2.THRESH_BINARY) lab = cv2.GaussianBlur(lab,(5,5),0) text = pytesseract.image_to_string(lab, lang="eng", config="--psm 6 digits") # print(f"Label{i}: {text}") try: ylabels[i] = float(text) except: pass label_images[i] = lab # cv2.imshow(f'label{i}', lab) if (ylabels.count(float('inf')) > len(ylabels) - 3): # Not enough points to perform linear interpolation # We suspect that the numbers are rotated 90 deg CCW for i,lab in enumerate(label_images): lab = imutils.rotate(lab, -90) lab = helper_functions.cropBlackBorder(lab) text = pytesseract.image_to_string(lab, lang="eng", config="--psm 6 digits") # print(f"Label{i}: {text}") try: ylabels[i] = float(text) except: pass label_images[i] = lab # cv2.imshow(f'label{i}', lab) # cv2.imshow('thresh', thresh) # cv2.imshow('dilate', dilate) # cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() zipped_y = zip(ypixels, ylabels) return list(zipped_y)
import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, 45, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by 45 degree", rotated) M = cv2.getRotationMatrix2D(center, -90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by -90 degree", rotated) cv2.waitKey(0) rotated = imutils.rotate(image, 180) cv2.imshow("Rotated by 180 degrees", rotated) cv2.waitKey(0)
args = vars(ap.parse_args()) server_ip = args['server_ip'] rotation = float(args['rotate']) # get the host name, initialize the video stream, and allow the # camera sensor to warmup rpiName = socket.gethostname() video_stream = VideoStream(usePiCamera=True).start() async_image_sender1 = AsyncImageSender(server_name=rpiName, server_ip=server_ip, port=5555, send_timeout=10, recv_timeout=10, show_frame_rate=10) image_count = 0 print("Press ctrl-c to stop image sending") sleep_time = 0.25 while True: frame = video_stream.read() if frame is not None: if rotation != 0: frame = imutils.rotate(frame, rotation) async_image_sender1.send_frame_immediate(frame) image_count += 1 time.sleep(sleep_time)
sumAreaDetect = [0, 0, 0] pointMove = [] lencnts = 0 pathToDB = "/home/pi/FaceRecognizer/sorted_output_images" #train #igen_model, people= faceRec.train_model(pathToDB) last_20 = [0 for i in range(20)] final_5 = [] box_text = "Subject: " while True: # Get the next frame. if args["video"] is None: frame = vs.read() frame = imutils.rotate(frame, 180) else: _, frame = vs.read() text = "Unoccupied" # If using a webcam instead of the Pi Camera, # we take the extra step to change frame size. if not usingPiCamera: frame = imutils.resize(frame, width=frameSize[0]) if (frame is None): print("not connect camera") break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) grayFace = cv2.equalizeHist(gray) """ faces = faceRec.detect_faces(grayFace)
# do Adrian Rosebrock resized_easy = imutils.resize(image, height=200) cv2.imshow("Redimensionamento com imutils", resized_easy) cv2.waitKey(0) # rotacionar uma imagem em 45 graus (sentido horário), calculando o centro da imagem, # construir uma matriz de rotação e finalmente aplicação o "warp affine" center = (w // 2, h // 2) rotation_matrix = cv2.getRotationMatrix2D(center, -45, 1.0) rotated = cv2.warpAffine(image, rotation_matrix, (w, h)) cv2.imshow("Rotação da imagem, com Rotation Matrix e Warp Affine", rotated) cv2.waitKey(0) # rotacionar uma imagem em 30 graus (sentido horário), usando a biblioteca imutils # do Adrian Rosebrock rotated_easy = imutils.rotate(image, -30) cv2.imshow("Rotação da imagem, com imutils", rotated_easy) cv2.waitKey(0) # rotacionar uma imagem em 45 graus (sentido horário), usando a biblioteca imutils # do Adrian Rosebrock, sem o cliping da mesma # Nesta função, o nível da rotação (em graus) deve ser o inverso (negativos - sentido antihorario, # positivos - sentido horário) rotated_bound = imutils.rotate_bound(image, 30) cv2.imshow("Rotação da imagem, com imutils, sem clipping", rotated_bound) cv2.waitKey(0) # aplicar Gaussian Blur na imagem, com um kernel de 11x11 para suavizar, # útil para reduzir "high frequency noise" blurred = cv2.GaussianBlur(image, (11, 11), 0) cv2.imshow("Borrada", blurred)
#from matplotlib import pyplot as plt # Running function parameters ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required=True) #lokasi gambar ap.add_argument('-j', '--parameter', required=True) #Jenis parameter ap.add_argument('-k', '--node', required=True) #nomor node args = vars(ap.parse_args()) eggparam = config[args["parameter"]][args["node"]] eggparam = eggparam.split(',') xcrop = int(eggparam[0]) ycrop = int(eggparam[1]) # Load, rotate and crop image img = cv2.imread(args["image"]) img = imutils.rotate(img, 180) h = img.shape[0] w = img.shape[1] img = img[0:h - ycrop, xcrop:w] # Convert image to HSV and Split to get value part hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hue, saturation, value = cv2.split(hsv) # Apply adaptive threshold with Gaussian thresh = cv2.adaptiveThreshold(value, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 255, 17) thresh = cv2.bitwise_not(thresh) # Detecting blobs as noise # Maximum blobs size
def read_digit(image_np,count,prev_reading): height = image_np.shape[1] width = image_np.shape[0] gray = cv2.cvtColor(image_np,cv2.COLOR_BGR2GRAY) plt.imshow(gray) plt.show() rot = imutils.rotate(gray,-90) plt.imshow(rot) plt.show() thresh = cv2.adaptiveThreshold(rot.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,31,13) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)) thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) # plt.imshow(thresh) # plt.show() im2, contours, hierarchy = cv2.findContours(thresh, 1, 2) cnt = max(contours, key = cv2.contourArea) #cnt = contours[0] M = cv2.moments(cnt) cimg = np.zeros_like(thresh) cv2.drawContours(cimg, contours, contours.index(cnt), color=255, thickness=-1) pts = np.where(cimg == 255) plt.imshow(cimg) plt.show() arr = zip(pts[0],pts[1]) #print M # cx = int(M['m10']/M['m00']) # cy = int(M['m01']/M['m00']) cx = width/2 cy = height /2 print('center: x %d y %d' %(cx,cy)) cv2.circle(rot,(cx,cy), 1, (0,0,255), -1) max_dist = 0 max_pixel = None for pixel in arr: dist = math.sqrt(((cx - pixel[0])**2) + ((cy - pixel[1])**2)) if dist > max_dist: max_pixel = pixel max_dist = dist print("max pixel: x %d y %d" %(max_pixel[1],max_pixel[0])) cv2.circle(rot,(max_pixel[1],max_pixel[0]), 1, (0,0,255), -1) plt.imshow(rot) plt.show() tx = max_pixel[1] ty = max_pixel[0] theta = math.atan2((ty-cy),(tx-cx)) phi = math.asin((cy - ty) / math.sqrt(((cy - ty)**2) + ((cx - tx) **2))) degrees = math.degrees(theta) if degrees >90 and degrees <=180: angle = (degrees -180) - 90 else: angle = degrees + 90 #print(theta) print("degress %f " %(math.degrees(theta))) print("actual angle %f" %(angle)) #print(phi) angle = angle % 360 print("circle angle %f" %(angle)) angle = float(angle) if angle>=0 and angle <= 36: if count % 2 == 0: reading = 0 else: reading = 9 elif angle > 36 and angle <= 72: if count % 2 == 0: reading = 1 else: reading = 8 elif angle > 72 and angle <=108: if count % 2 == 0: reading = 2 else: reading = 7 elif angle > 108 and angle <= 144: if count % 2 == 0: reading = 3 else: reading = 6 elif angle > 144 and angle <= 180: if count % 2 == 0: reading = 4 else: reading = 5 elif angle > 180 and angle <=216: if count % 2 == 0: reading = 5 else: reading = 4 elif angle > 216 and angle <=252: if count % 2 == 0: reading = 6 else: reading = 3 elif angle > 252 and angle <= 288: if count % 2 == 0: reading = 7 else: reading = 2 elif angle > 288 and angle <= 324: if count % 2 == 0: reading = 8 else: reading = 1 elif angle > 324 and angle < 360: if count % 2 == 0: reading = 9 else: reading = 0 # edge cases where the dial is close to a number # must take into account previous reading to adjust for accuracy if(prev_reading!=-1): if((angle > 350 and angle<360) or angle < 10): if (count %2 ==0): if(prev_reading >= 5): reading = 9 else: reading = 0 else: if(prev_reading >=5): reading = 9 else: reading = 0 elif(angle > 26 and angle <=46): if count %2 ==0: if(prev_reading >= 5): reading = 0 else: reading = 1 else: if(prev_reading >=5): reading = 8 else: reading = 9 elif(angle > 62 and angle < 82): if count %2 ==0: if(prev_reading >= 5): reading = 1 else: reading = 2 else: if(prev_reading >=5): reading = 7 else: reading = 8 elif(angle > 98 and angle < 118): if count %2 ==0: if(prev_reading >= 5): reading = 2 else: reading = 3 else: if(prev_reading >=5): reading = 6 else: reading = 7 elif(angle > 134 and angle < 154): if count %2 ==0: if(prev_reading >= 5): reading = 3 else: reading = 4 else: if(prev_reading >=5): reading = 5 else: reading = 6 elif(angle > 170 and angle < 190): if count %2 ==0: if(prev_reading >= 5): reading = 4 else: reading = 5 else: if(prev_reading >=5): reading = 4 else: reading = 5 elif(angle > 206 and angle < 226): if count %2 ==0: if(prev_reading >= 5): reading = 5 else: reading = 6 else: if(prev_reading >= 5): reading = 3 else: reading = 4 elif(angle > 242 and angle < 262): if count %2 ==0: if(prev_reading >= 5): reading = 6 else: reading = 7 else: if(prev_reading >= 5): reading = 2 else: reading = 3 elif(angle > 278 and angle < 298): if count %2 ==0: if(prev_reading >= 5): reading = 7 else: reading = 8 else: if(prev_reading >=5): reading = 1 else: reading = 2 elif(angle > 314 and angle < 334): if count %2 ==0: if(prev_reading >= 5): reading = 8 else: reading = 9 else: if(prev_reading >= 5): reading = 0 else: reading = 1 print(reading) return reading
ap.add_argument("-i", "--image", required=True, help="Path to image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) cv2.waitKey(0) shifted = imutils.translate(image, 25, 50) # cv2.imshow('Shifted Down and Right', shifted) # cv2.waitKey(0) shifted = imutils.translate(image, -25, -50) # cv2.imshow('Shifted Up and Left', shifted) # cv2.waitKey(0) rotated = imutils.rotate(image, 45) # cv2.imshow('Rotated 45 degree', rotated) # cv2.waitKey(0) resized = imutils.resize(image, height=150) # cv2.imshow('Resized to height 150', resized) # cv2.waitKey(0) flipped = cv2.flip(image, 1) # cv2.imshow('Flipped Horizontally', flipped) # cv2.waitKey(0) flipped = cv2.flip(image, 0) # cv2.imshow('Flipped Vertically', flipped) # cv2.waitKey(0)
def rotateflipImg(Rotation_Angle=Rotation_Angle, Flip_X=Flip_X, noise_level=noise_level, step=step): # do_rotateflipImg # def rotateflipImg(Rotation_Angle,Flip_X,noise_level,step): print 'doing rotation or flipping', Rotation_Angle, ',', Flip_X, ',st', step, \ ',noise=', noise_level, ',do_perspectiveTransform_in=', do_perspectiveTransform_in print 'removing tmp data' for i in xrange(len(settings.LABELS)): dir = settings.tmp + settings.LABELS[i] for f in os.listdir(dir): if re.search('/*.jpg', f) is not None: os.remove(os.path.join(dir, f)) filelist = glob.glob(INPUT_PATCHES_PATH + '/*') # print 'filelist,', filelist for filename in filelist: for label in settings.LABELS: if string.find(filename + '/', label) != -1: # hy:return index if found, or -1 if not found INPUT_PATH = INPUT_PATCHES_PATH + label OUTPUT_PATH = DATA_PATH + label if DEBUG: print 'If error occurs, possibly because some old file name errors, e.g. contain _ in the end' # hy: copy patches to tmp folders #cmd = 'cp -r ' + INPUT_PATH + '*' + ' ' + tmp_PATH + label # hy: copy recursively #os.system(cmd) filelist_tmp = glob.glob(INPUT_PATCHES_PATH + label + '*') #filelist_tmp = glob.glob(tmp_PATH + label + '*') random.shuffle(filelist_tmp) # hy:use fixed additional amount of data # random_add = 1 # random_add = 7*len(settings.LABELS) # hy: use proportional setting # random_add = int(len(filelist_tmp) * 0.70) filelist_add = filelist_tmp[0:random_add] # print len(filelist_tmp) # for file in filelist_tmp: #hy if all data should be used for file in filelist_add: # hy if only part data should be used file.split('/')[-1] # print file.split('/')[-1] original = cv2.imread(file) Height, Width, Channel = original.shape # print original.shape ### Rotation start ############################################################## if Anti_clockwise == 1 and Rotation_Angle <> 0: # Counter-Clockwise: Zooming in, rotating, cropping # rotated_tmp = cv2.resize(original, (Width + 40, Height + 20), interpolation=cv2.INTER_LINEAR) # rotated_tmp = imutils.rotate(rotated_tmp, angle=Rotation_Angle) # rotated = rotated_tmp[10:Height + 10, 20:Width + 20] # print rotated.shape # rotated = imutils.resize(rotated, width=Width, # height=Height) rotated = imutils.rotate(original, angle=Rotation_Angle) new_file = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_st' + str( step) + '_rotatedCC_' + str( Rotation_Angle) + ImageType # hy: split by .jpg, with '.' to avoid extra '.' in file name cv2.imwrite(new_file, rotated) if Clockwise == 1 and Rotation_Angle <> 0: # Clockwise rotated_tmp = cv2.resize(original, (Width + 40, Height + 20), interpolation=cv2.INTER_LINEAR) rotated_tmp = imutils.rotate(rotated_tmp, angle=Rotation_Angle * -1) rotated = rotated_tmp[10:Height + 10, 20:Width + 20] # print rotated.shape rotated = imutils.resize(rotated, width=Width, height=Height) new_file = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_st' + str( step) + '_rotatedC_' + str(Rotation_Angle) + ImageType cv2.imwrite(new_file, rotated) ### Rotation end ############################################################## ### Flipping begin ############################################################## if Flip_X == 1: flipped = cv2.flip(original, 0) new_file = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_flippedX' + ImageType cv2.imwrite(new_file, flipped) if Flip_Y == 1: flipped = cv2.flip(original, 1) new_file = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_flippedY' + ImageType cv2.imwrite(new_file, flipped) if Flip_XY == 1: flipped = cv2.flip(original, -1) new_file = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_flippedXY' + ImageType cv2.imwrite(new_file, flipped) ### Flipping end ############################################################## ### Perspective Transform begin ################################################# f_outs = [] if do_perspectiveTransform_in == 1: # print 'file',file # h, w, ch = original.shape # print 'h,w,ch', h, w, ch # rand1 = randint(2,30) # rand2 = randint(2,30) aspect_w = int(Aspect_Factor * Width) for i in xrange(aspect_w, aspect_w + 2): for j in xrange(14, 16): pts1 = np.float32([[i, 0], [Width - i, 0], [j, Height - j], [Width - i, Height - j]]) # pts1 = np.float32([[rand1, 0], [patch_size+rand1, 0], [rand2, patch_size], [patch_size, patch_size]]) pts2 = np.float32([[0, 0], [Width, 0], [0, Height], [Width, Height]]) # leftT,rT,leftB,rB # pts2 = np.float32([[0, 0], [patch_size, 0], [0, patch_size], [patch_size, patch_size]]) # leftT,rT,leftB,rB M = cv2.getPerspectiveTransform(pts1, pts2) dst = cv2.warpPerspective(original, M, (Width, Height)) # (w,h) # dst = cv2.warpPerspective(img,M,(patch_size,patch_size)) #(w,h) f_out = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_persp_' + str(i) + '_' + str( j) + ImageType # f_out = '../Data/data_1_mix/save/prep/' + os.path.basename(file) + '_persp_' + str(i) + '_' + str(j) + ImageType print f_out f_outs.append(f_out) cv2.imwrite(f_out, dst) print 'can generate num of new files with perspective transformation', len(f_outs) ### Perspective Transform end ################################################# ### add noise begin ############################################################## if noise_level <> 0: img_gray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY) # img = img.astype(np.float32) img_noised = img_gray + np.random.rand(Width, Height) * noise_level img_noised = (img_noised / np.max(img_noised)) * 255 new_file = OUTPUT_PATH + os.path.basename(os.path.normpath(file))[:-4] + '_st' + str( step) + '_NOI' + ImageType cv2.imwrite(new_file, img_noised)
# translate the image x-50 pixels to the left and y=100 pixels down translated = imutils.translate(workspace, -50, 100) cv2.imshow("Translated", translated) cv2.waitKey(0) # translate the image x=25 pixels to the right and y=75 pixels up translated = imutils.translate(workspace, 25, -75) cv2.imshow("Translated", translated) cv2.waitKey(0) cv2.destroyAllWindows() # 2. ROTATION # loop over the angles to rotate the image for angle in range(0, 360, 90): # rotate the image and display it rotated = imutils.rotate(bridge, angle=angle) cv2.imshow("Angle=%d" % (angle), rotated) # wait for a keypress, then close all the windows cv2.waitKey(0) cv2.destroyAllWindows() # 3. RESIZING # loop over varying widths to resize the image to for width in (400, 300, 200, 100): # resize the image and display it resized = imutils.resize(workspace, width=width) cv2.imshow("Width=%dpx" % (width), resized) # wait for a keypress, then close all the windows cv2.waitKey(0)
def rotate(image, x): #image = imutils.rotate_bound(image, -1) # not cutting information off image = imutils.rotate(image, -x) return image
#frame = cv2.imread(sys.argv[1]) # load the games image #image = cv2.imread("tower.jpeg") camera = cv2.VideoCapture(0) #loop while True: #grabs current frame (grabbed, frame) = camera.read() #resizes video frame = imutils.resize(frame, width = 300) frame = imutils.rotate(frame, 180) # find the red color game in the image upper = [200,250,0] lower = [20,180,0] upper = np.array(upper,dtype = "uint8") lower = np.array(lower,dtype = "uint8") mask = cv2.inRange(frame, lower, upper) #find contours in the masked frame and keep the largest one (_, cnts, _) = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) leftmost = (0, 0) rightmost = (0, 0) topmost = (0, 0) bottommost = (0, 0)
def OCR_Analyser(path, imageno): imageno = "" image = cv2.imread(path) #Resigning the image to below dim as it has been found best during training. dim = (348, 129) image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) imageoriginal = image image = get_grayscale(image) avgthresh = findavg(image) cv2.imshow('1-GrayScale:' + str(imageno), image) cv2.waitKey(0) imagethresh = thresholding(image, avgthresh) imagethresh = opening(imagethresh) cv2.imshow('2-Threshold:' + str(imageno), imagethresh) cv2.waitKey(0) c = image contours, hierarchy = cv2.findContours(imagethresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) val = -1 count = 0 for i in contours: if len(i) == 4: val = count break count = count + 1 if len(contours) == 0: #print("###############################") return "", imagethresh c = max(contours, key=cv2.contourArea) cv2.drawContours(imageoriginal, c, -1, (0, 255, 0), 3) cv2.imshow('3-Contours:' + str(imageno), imageoriginal) cv2.waitKey(0) rect = cv2.minAreaRect(c) #Finds angle and rotates the image so that its horizontal. angle = rect[-1] if abs(angle) < 90 - abs(angle): angle = angle else: if angle < 0: angle = 90 - abs(angle) else: angle = abs(angle) - 90 ##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% imageproc = imutils.rotate(imagethresh, angle) contours, hierarchy = cv2.findContours(imageproc.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) c = max(contours, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(c) cv2.drawContours(imageoriginal, c, -1, (0, 255, 0), 3) imageproc = imageproc[y:y + h, x:x + w] imageproc = erode(imageproc) #imageproc = cv2.medianBlur(imageproc,3) #imageproc=erode(imageproc) #imageproc=dilate(imageproc) #After Analysis I found pytesseract works best with dim= (385,90) imageproc = cv2.resize(imageproc, (385, 90), interpolation=cv2.INTER_AREA) #print("previous:",imageproc) for i in range(11): for j in range(384): imageproc[i][j] = 255 imageproc[89 - i][j] = 255 for i in range(22): for k in range(89): imageproc[k][i] = 255 imageproc[k][384 - i] = 255 #Pytesseract configuration oem = 0 #Legacy system psm = 7 #Treats image as single text line custom_config = r'--oem ' + str(oem) + ' --psm ' + str( psm ) + '-c tessedit_char_whitelist=012345679abcdefghijklmnopqrstuvwlyz tessedit_char_blacklist=.-!/' value = pytesseract.image_to_string(imageproc, lang='eng', config=custom_config) value = value.encode('ascii', 'ignore') cv2.imshow('4 - OCRImage:' + str(imageno), imageproc) cv2.waitKey(0) value = value.split() finalresult = [] if len(value) > 2: strval = " " for i in value: strval = strval + str(i) + " " finalresult = strval else: firstword = firstwordpostprocessing(value) secondword = "" if len(value) > 0 and len(value) > 1: secondword = secondwordpostprocessing(value) #print("Firstword:",firstword) #print("secondword:",secondword) #print("Type of firstword:",type(str(firstword))) #print("Type of secondword:",type(secondword)) finalresult = str(firstword) + " " + str(secondword) return finalresult, imageproc
ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) # (h, w) = image.shape[:2] # <~ clever way to get the height and width! # center = (w // 2, h // 2) # m1 = cv2.getRotationMatrix2D(center, 45, 1.0) # rotated_up = cv2.warpAffine(image, m1, (w, h)) # cv2.imshow("Rotated by 45 Degrees", rotated_up) # cv2.waitKey(0) # m2 = cv2.getRotationMatrix2D(center, -90, 1.0) # rotated_down = cv2.warpAffine(image, m2, (w, h)) # cv2.imshow("Rotated by -90 Degrees", rotated_down) # cv2.waitKey(0) rotated_up = imutils.rotate(image, 45, None, 1.0) cv2.imshow("Rotated by 45 Degrees", rotated_up) cv2.waitKey(0) rotated_down = imutils.rotate(image, -90, None, 1.0) cv2.imshow("Rotated by -90 Degrees", rotated_down) cv2.waitKey(0) cv2.waitKey(0)
import numpy as np import argparse import imutils import cv2 ap=argparse.ArgumentParser() ap.add_argument("-i","--image",required=True,help ="Path to the Image") args=vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original",image) rotated = imutils.rotate(image,45,center=(50,40),scale=2.0) cv2.imshow("rotated", rotated) cv2.waitKey(0)
# Construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) # Load the image and show it image = cv2.imread(args["image"]) cv2.imshow("Original", image) # Grab the dimensions of the image and calculate the center # of the image (h, w) = image.shape[:2] center = (w / 2, h / 2) # Rotate our image by 45 degrees M = cv2.getRotationMatrix2D(center, 45, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by 45 Degrees", rotated) # Rotate our image by -90 degrees M = cv2.getRotationMatrix2D(center, -90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by -90 Degrees", rotated) # Finally, let's use our helper function in imutils.py to # rotate the image by 180 degrees (flipping it upside down) rotated = imutils.rotate(image, 180) cv2.imshow("Rotated by 180 Degrees", rotated) cv2.waitKey(0)
import cv2 import numpy as np import matplotlib.pyplot as plt import imutils import math width = 300 height = 300 filename = 'analog.jpeg' org = cv2.imread(filename) gray = cv2.cvtColor(org,cv2.COLOR_BGR2GRAY) #gray = cv2.GaussianBlur(gray, (9, 9), 2,2) img = imutils.resize(gray,width=300,height=300) rot = imutils.rotate(img,-90) # detect circles in the image # circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, param1=100,param2=100) # # ensure at least some circles were found # if circles is not None: # # convert the (x, y) coordinates and radius of the circles to integers # circles = np.round(circles[0, :]).astype("int") # # loop over the (x, y) coordinates and radius of the circles # for (x, y, r) in circles: # # draw the circle in the output image, then draw a rectangle # # corresponding to the center of the circle
def read_images_online(filelist='',random_read=True,Anti_clockwise=0,Clockwise=0,Rotation_Angle=0,Flip_X=0,Flip_Y=0,noise_level=0,step=0): print filelist,random_read,Anti_clockwise,Clockwise,Rotation_Angle,Flip_X,Flip_Y,noise_level,step lable_file = open(filelist,'r') lines = lable_file.readlines() if random_read == True: # make the file order in random way, this makes training more efficiently random.shuffle(lines) print 'loading images in random order' else: print 'loading sorted images' images=[] labels=[] files=[] label_sum=0 for item in lines: filename,label = item.split() #print filename im = cv2.imread(filename) im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) #im = imutils.resize(im, width = 72, height = 72) # w=146, h=121 im = imutils.resize(im, width = settings.w_resize, height = settings.h_resize) # w=146, h=121 (settings.h_resize, settings.w_resize) = im.shape #hy:get suitable value for width im=np.asarray(im, np.float32) images.append(im) labels.append(label) files.append(filename) ############ add online data begin # Rotation_Angle = randint(15, 170) # noise_level = 0.01 * randint(1, 2) ### Rotation start ############################################################## if Anti_clockwise == 1 and Rotation_Angle <> 0: rotated = imutils.rotate(im, angle=Rotation_Angle) images.append(rotated) labels.append(label) files.append(filename) if Clockwise == 1 and Rotation_Angle <> 0: # Clockwise rotated_tmp = cv2.resize(im, (settings.w_resize + 40, settings.h_resize + 20), interpolation=cv2.INTER_LINEAR) rotated_tmp = imutils.rotate(rotated_tmp, angle=Rotation_Angle * -1) rotated = rotated_tmp[10:settings.h_resize + 10, 20:settings.w_resize + 20] # print rotated.shape rotated = imutils.resize(rotated, width=settings.w_resize, height=settings.h_resize) images.append(rotated) labels.append(label) files.append(filename) ### Rotation end ############################################################## ### Flipping begin ############################################################## if Flip_X == 1: flipped = cv2.flip(im, 0) images.append(flipped) labels.append(label) files.append(filename) if Flip_Y == 1: flipped = cv2.flip(im, 1) images.append(flipped) labels.append(label) files.append(filename) ### Flipping end ############################################################## ### add noise begin ############################################################## if noise_level <> 0: img_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) # img = img.astype(np.float32) img_noised = img_gray + np.random.rand(settings.w_resize, settings.h_resize) * noise_level img_noised = (img_noised / np.max(img_noised)) * 255 ### add noise end ############################################################## ############ add online data end label_sum += int(label) images_np = np.asarray(images) labels_np = np.asarray(labels) return (images_np, labels_np, files)
cv2.imshow("Binary", img_out) if pre[3] in PRE: img_out = extract_contours(img_out) cv2.imshow("Remove Contour", img_out) cv2.waitKey(20000) cv2.destroyAllWindows() angle = 361 if MODE == modes[0]: # projection angle = projection(img_out) elif MODE == modes[1]: # hough angle = hough(img_out) rotated = imutils.rotate(img_orig, angle) cv2.imshow("Rotated", rotated) text = pytesseract.image_to_string(rotated) print("Texto apos da rotação:") print(text) if angle >= 0: print("Inclinação de %d° no sentido horário" % angle) else: print("Inclinação de %d° no sentido anti-horário" % (-angle)) if OUTPUT: cv2.imwrite(OUTPUT, rotated) cv2.waitKey(0)
import numpy as np import imutils import cv2 # Load an color image in grayscale #img = cv2.imread('/home/hamed/WheelChair_Detect_copy/Data/Kiwa/2015-12-10_10.49_21.1.cam_81_1_020220.jpg') img = cv2.imread('/home/hamed/Documents/Lego_copy/Data/hinten/20160421_133435_croppad_227_1_1.jpg') cv2.imshow("test",img) rotated=imutils.rotate(img,angle=5) cv2.imshow("Rotated",rotated) gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("Gray",gray) grayEq=gray cv2.equalizeHist(gray, grayEq) cv2.imshow("GrayEq", grayEq) gray=cv2.flip(grayEq,-1) cv2.imshow("flipped",gray) cv2.imshow("reesize",imutils.resize(imutils.resize(gray,width=84),width=210)) #hy:updated size as per the example image old value 84,210 cv2.waitKey(0)
if key_input[pygame.K_ESCAPE]: salir() pygame.display.update() fpsclock.tick(fps) log() # -- 2. Read the video stream cap = cv.VideoCapture(0) if not cap.isOpened: print('--(!)Error opening video capture') exit(0) while True: ret, frame = cap.read() if frame is None: print('--(!) No captured frame -- Break!') break fps = cap.get(5) cv.putText(frame, str(fps), (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255)) frame = imutils.rotate(frame, 180 - pos_pan) cv.imshow('Capture - Rotate on pan', frame) if cv.waitKey(1) == ord('q'): break mover_pygame()
def detect_landmarks(img): import face_alignment import imutils import numpy as np import dlib import cv2 fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=False) p = "shape_predictor_68_face_landmarks.dat" detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(p) res = cv2.resize(img, dsize=(80, 80), interpolation=cv2.INTER_CUBIC) landmarks = np.empty([]) rects = detector(res, 0) if (len(rects)) != 0: rect = rects[0] landmarks = predictor(res, rect) landmarks = process_landmarks(landmarks) landmarks = 0.55 * np.array(landmarks) else: rotated = imutils.rotate(res, 90) rects = detector(rotated, 0) if (len(rects)) != 0: rect = rects[0] landmarks = predictor(rotated, rect) landmarks = process_landmarks(landmarks) landmarks = 0.55 * np.array(landmarks) else: rotated = imutils.rotate(res, -90) rects = detector(rotated, 0) if (len(rects)) != 0: rect = rects[0] landmarks = predictor(rotated, rect) landmarks = process_landmarks(landmarks) landmarks = 0.55 * np.array(landmarks) else: preds = fa.get_landmarks(img) if preds is not None: points = preds[0] potints = np.array(points) landmarks = [] xl = [] yl = [] for i in range(0, 68): xl.append(points[i, 0]) yl.append(points[i, 1]) xmean = np.mean(xl) ymean = np.mean(yl) xcentral = [(x - xmean) for x in xl] ycentral = [(y - ymean) for y in yl] for j in range(0, 68): for k in range(j + 1, 68): if j != k: distx = (xcentral[j] - xcentral[k]) disty = (ycentral[j] - ycentral[k]) landmarks.append(distx) landmarks.append(disty) landmarks = np.array(landmarks) else: preds = fa.get_landmarks(res) if preds is not None: points = preds[0] potints = np.array(points) landmarks = [] xl = [] yl = [] for i in range(0, 68): xl.append(points[i, 0]) yl.append(points[i, 1]) xmean = np.mean(xl) ymean = np.mean(yl) xcentral = [(x - xmean) for x in xl] ycentral = [(y - ymean) for y in yl] for j in range(0, 68): for k in range(j + 1, 68): if j != k: distx = (xcentral[j] - xcentral[k]) disty = (ycentral[j] - ycentral[k]) landmarks.append(distx) landmarks.append(disty) landmarks = 0.55 * np.array(landmarks) #print('Face align size: '+str(landmarks.size)) return landmarks
def face_recognition(): while not (GPIO.input(11) or GPIO.input(13) or GPIO.input(15)): #while True: print("yes3") cam.capture("/home/pi/Desktop/switch/face1.png") #img = np.asarray(Image.open("/home/pi/Desktop/switch/FacialRecognitionProject/face1.png")) #img =cam.read() img = cv2.imread("/home/pi/Desktop/switch/face1.png") img = cv2.flip(img, -1) # Flip vertically img = imutils.rotate(img, angle=180) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=5, minSize=(int(minW), int(minH)), ) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) r = (2 * x + w) / 2 id, confidence = recognizer.predict(gray[y:y + h, x:x + w]) # Check if confidence is less them 100 ==> "0" is perfect match if ((100 - confidence) > 40): id = names[id] confidence = " {0}%".format(round(100 - confidence)) if (r > 540): engine = pyttsx3.init() engine.say("go left") engine.say("it's " + str(id)) engine.runAndWait() else: engine = pyttsx3.init() engine.say("go right") engine.say("it's " + str(id)) engine.runAndWait() #file1 = open("MyFile.txt","a") #file1.write("\n"+str(id)+ " at: "+str(datetime.datetime.now())) else: id = "unknown" confidence = " {0}%".format(round(100 - confidence)) if (r > 540): engine = pyttsx3.init() engine.say("go left") engine.runAndWait() else: engine = pyttsx3.init() engine.say("go right") engine.runAndWait() cv2.putText(img, str(id), (x + 5, y - 5), font, 1, (255, 255, 255), 2) cv2.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (255, 255, 0), 1) cv2.imshow('camera', img) print("yes3") #if str(id)!= "unknown": # speechCallName(str(id)) k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video if k == 27: break
import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required=True, help="Path") args = vars(ap.parse_args()) image = cv2.imread(args['image']) cv2.imshow("Oriji", image) (h, w) = image.shape[:2] centre = (w // 2, h // 2) M = cv2.getRotationMatrix2D(centre, 45, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("45", rotated) M = cv2.getRotationMatrix2D(centre, -90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("-90", rotated) image = imutils.rotate(image, centre, 200, 2, w, h) cv2.imshow("270", image) cv2.waitKey(0)
while cap.isOpened(): ret,frame = cap.read() if ret == True: cv2.imshow('window-name',frame) cv2.imwrite("./output/frame%d.jpg" % count, frame) count = count + 1 if cv2.waitKey(10) & 0xFF == ord('q'): break else: break cap.release() cv2.destroyAllWindows() # car image -> grayscale image -> binary image car_image = imread("./output/frame%d.jpg"%(count-1), as_gray=True) car_image = imutils.rotate(car_image, 270) # car_image = imread("car.png", as_gray=True) # it should be a 2 dimensional array print(car_image.shape) ''' the next line is not compulsory however, a grey scale pixel in skimage ranges between 0 & 1. multiplying it with 255 will make it range between 0 & 255 (something we can relate better with ''' gray_car_image = car_image * 255 fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(gray_car_image, cmap="gray") threshold_value = threshold_otsu(gray_car_image) binary_car_image = gray_car_image > threshold_value
import argparse import cv2 import imutils ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required=True, help='Path to input image') args = vars(ap.parse_args()) image = cv2.imread(args['image']) #cv2.imshow('Image', image) flipped = cv2.flip(image, 1) cv2.imshow('Flipped', flipped) print(flipped[235, 259]) rotated = imutils.rotate(flipped, 45) flipped = cv2.flip(rotated, 0) cv2.imshow('Flipped', flipped) print(flipped[189, 441]) #flipped = cv2.flip(image, -1) #cv2.imshow('F # lipped', flipped) cv2.waitKey(0)
def detect(request): s=str(request.method) fil=[] print("request files",request.FILES) for x in request.FILES: fil.append(str(request.FILES[x])) for y in fil: from time import time t1=time() im=cv.imread(y) #im=imutils.rotate(im,-90) #im=im[im.shape[1]//2:,:] obj,lst=object_detect(im) tobj=obj tobj=imutils.rotate(tobj,-90) print("time for object detection",time()-t1) img=lanedetect(tobj) #img=imutils.rotate(img,90) for l in lst: l.assign_dist(calc_distance(l.middle_x,l.middle_y)) #l.assign_offset() try: nearest_obstacle=find_nearest_obstacle(lst) except Exception as e: print("In calling function") print(e) try: cv2.line(obj,(int(pt[0]),int(pt[1])),(nearest_obstacle['middle_x'],nearest_obstacle['middle_y']),5) except Exception as e: print(e) cv2.imshow("image",obj) cv2.waitKey(0) data = {"success": False,"hiii":"hello","method":s,"File":fil} data['offset']=getOffsetStatus() data['obstacles']=findObstaclesInPath(nearest_obstacle) return JsonResponse(data)
plt.yticks([]) # ------------------------------------ a = fig.add_subplot(2, 3, 4) imgplot = plt.imshow(imageInputOrig) a.set_title('Before') plt.xticks([]) plt.yticks([]) a = fig.add_subplot(2, 3, 5) imgplot = plt.imshow(whiteImg) a.set_title('Landmarks') plt.xticks([]) plt.yticks([]) imageInput = imutils.rotate(imageInput, 45) a = fig.add_subplot(2, 3, 6) imgplot = plt.imshow(newImage) a.set_title('After') plt.xticks([]) plt.yticks([]) fname = "results/" + "result_" + args["image"][1] plt.show() ''' plt.imshow(imageInput)
limpiar(); print("#########################################################"); # Ej 016_16 print("Inicio ej016_16 - "); center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, -45, 1.0) rotated = cv2.warpAffine(imagen, M, (w, h)) cv2.imshow("Opencv2 Rotation", rotated) cv2.waitKey(1500) cv2.destroyAllWindows() #print (input("Fin ej016_16 \n continuar?")); limpiar(); print("#########################################################"); # Ej 016_17 print("Inicio ej016_17 - "); rotated = imutils.rotate(imagen, 45) cv2.imshow("Imutils Rotation", rotated) cv2.waitKey(1500) cv2.destroyAllWindows() #print (input("Fin ej016_18 \n continuar?")); limpiar(); print("#########################################################"); # Ej 016_18 print("Inicio ej016_18 - "); blurred = cv2.GaussianBlur(imagen, (11, 11), 0) cv2.imshow("Blurred", blurred) cv2.waitKey(1500) cv2.destroyAllWindows() #print (input("Fin ej016_18 \n continuar?")); limpiar(); print("#########################################################");
rotated = cv2.warpAffine(img, M, (w, h)) cv2.imshow("rotated", rotated) #by 90 degree and scale 0.5 M = cv2.getRotationMatrix2D((cX, cY), 90, 0.5) rotated2 = cv2.warpAffine(img, M, (w, h)) cv2.imshow("rotated2", rotated2) #by -90 degree and scale 2.0 (double) M = cv2.getRotationMatrix2D((cX, cY), -90, 2.0) rotated3 = cv2.warpAffine(img, M, (w, h)) cv2.imshow("rotated3", rotated3) #using image utils lib rotated_utils = imutils.rotate(img, 180, None, 0.5) cv2.imshow("rotated_utils", rotated_utils) """ def rotate(img,angle,center=None,scale=1.0): h,w = img.shape[:2] if center is None: center = (w//2,h//2) M = cv2.getRotationMatrix2D(center,angle,scale) rotate = cv2.wrapAffine(img,M,(w,h)) return rotate """
import cv2 # Read the existing image. image_packet = impb.Image() try: f = open("image_data.proto.bin", "rb") image_packet.ParseFromString(f.read()) f.close() except IOError: print("image_data.proto.bin" + ": Could not open file.") with open('picture_out.jpg', 'wb') as f: f.write(image_packet.image_data) image_transform = cv2.imread("picture_out.jpg") (h, w, d) = image_transform.shape print("width={}, height={}, depth={}".format(w, h, d)) (B, G, R) = image_transform[100, 50] print("R={}, G={}, B={}".format(R, G, B)) roi = image_transform[60:160, 320:420] resized = cv2.resize(image_transform, (100, 100)) rotated = imutils.rotate(image_transform, -45) #with open('picture_out.jpg', 'wb') as imagefile: #imagefile.write(bytearray(image_packet.SerializeToString())) #bytesIOImage = io.BytesIO(bytearray(image_packet.SerializeToString())) #bytesIOImage.seek(0) #image = Image.open(bytesIOImage) #image.save('picture_out.jpg')
nargs='+', help="height and width to crop") ap.add_argument("-r", "--ratio", required=True, help="ratio for shrinking") args = ap.parse_args() workingPath = args.srcPath targetPath = args.tgtPath ang = float(args.angle) cp = args.cropPercent r = float(args.ratio) # print(float(cp[1])) imageFiles = os.listdir(workingPath) rgbIm = [] for im in imageFiles: if im.find(".jpg") != -1: rgbIm.append(im) # Detect each individual image for imf in rgbIm: imgFile = cv2.imread(workingPath + "\\" + imf) rotated = imutils.rotate(imgFile, ang) imgCrop = rotated[(int(rotated.shape[0] * (float(cp[0])))):(int(rotated.shape[0] * (float(cp[1]))) - 1), (int(rotated.shape[1] * (float(cp[2])))):(int(rotated.shape[1] * (float(cp[3]))) - 1)] resizedImage = cv2.resize( imgCrop, (int(imgCrop.shape[1] * r), int(imgCrop.shape[0] * r)), interpolation=cv2.INTER_AREA) print(targetPath + "\\" + imf) cv2.imwrite(targetPath + "\\" + imf, resizedImage)
cv2.imshow("Imutils Resize", resized) cv2.waitKey(0) # let's rotate an image 45 degrees clockwise using OpenCV by first # computing the image center, then constructing the rotation matrix, # and then finally applying the affine warp center = (w // 2, h // 2) """ cv2.getRotationMatrix2D(center, angle, scale) """ M = cv2.getRotationMatrix2D(center, -45, 1.0) """ cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) """ rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("OpenCV Rotation", rotated) cv2.waitKey(0) # rotation can also be easily accomplished via imutils with less code rotated = imutils.rotate(image, -45) cv2.imshow("Imutils Rotation", rotated) cv2.waitKey(0) # OpenCV doesn't "care" if our rotated image is clipped after rotation # so we can instead use another imutils convenience function to help # us out rotated = imutils.rotate_bound(image, 45) cv2.imshow("Imutils Bound Rotation", rotated) cv2.waitKey(0) # apply a Gaussian blur with a 11x11 kernel to the image to smooth it, # useful when reducing high frequency noise """ cv2.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType]]])kSize es """ blurred = cv2.GaussianBlur(image, (11, 11), 0) cv2.imshow("Blurred", blurred)
nW = int((w * cos) + (h * sin)) nH = int((w * sin) + (h * cos)) M[0, 2] += (nW / 2) - cX M[1, 2] += (nH / 2) - cY return cv2.warpAffine(image, M, (nW, nH)) ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the image file") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) for angle in np.arange(0, 360, 15): rotated = imutils.rotate(image, -angle) cv2.imshow("Rotated (problematic)", rotated) cv2.waitKey(500) for angle in np.arange(0, 360, 15): rotated = imutils.rotate_bound(image, angle) cv2.imshow("Rotated (Correct)", rotated) cv2.waitKey(500) for angle in np.arange(0, 360, 15): rotated = rotate_bound_mine(image, angle) cv2.imshow("Rotated (Correct)", rotated) cv2.waitKey(500)
def rotation_not_90_func(img, label, thetha): rotated = imutils.rotate(img, thetha) rotated_label = imutils.rotate(label, thetha) return rotate_max_area(img, rotated, rotated_label, thetha)
def orientation(): rotation_ratio = 72 angles = 5 myList = [None] * rotation_ratio mask1List = [None] * rotation_ratio rotate1List = [None] * rotation_ratio mask2List = [None] * rotation_ratio rotate2List = [None] * rotation_ratio blackPixList = [None] * rotation_ratio differList = [None] * rotation_ratio i = j = k = 0 lower = [(0, 100, 100)] upper = [(100, 255, 255)] img1 = cv.imread('images_temp/normal_crop_img.jpg') img2 = cv.imread('images_temp/saved_img.jpg') for mask2angle in np.arange(0, 360, angles): rotate2List[int(j)] = imutils.rotate(img2, mask2angle) edged2 = cv.Canny(rotate2List[j], 0, 200) pts2 = np.argwhere(edged2 > 0) y12, x12 = pts2.min(axis=0) y22, x22 = pts2.max(axis=0) mask2List[int(j)] = y22 j = j + 1 for mask1angle in np.arange(0, 360, angles): rotate1List[int(k)] = imutils.rotate(img1, mask1angle) edged1 = cv.Canny(rotate1List[k], 0, 200) pts1 = np.argwhere(edged1 > 0) y11, x11 = pts1.min(axis=0) y21, x21 = pts1.max(axis=0) mask1List[int(k)] = y21 k = k + 1 edged1 = cv.Canny(rotate1List[mask1List.index(min(mask1List))], 0, 200) edged2 = cv.Canny(rotate2List[mask2List.index(min(mask2List))], 0, 200) #150 550 # 0 200 pts1 = np.argwhere(edged1 > 0) pts2 = np.argwhere(edged2 > 0) y11, x11 = pts1.min(axis=0) y12, x12 = pts2.min(axis=0) y21, x21 = pts1.max(axis=0) y22, x22 = pts2.max(axis=0) croppedimg1 = rotate1List[mask1List.index(min(mask1List))][y11:y21, x11:x21] croppedimg2 = rotate2List[mask2List.index(min(mask2List))][y12:y22, x12:x22] lower = np.array(lower, dtype="uint8") upper = np.array(upper, dtype="uint8") mask1 = cv.inRange(croppedimg1, lower, upper) mask2 = cv.inRange(croppedimg2, lower, upper) img_shape1 = croppedimg1.shape img_shape2 = croppedimg2.shape if img_shape1 == img_shape2: crop_mask1 = mask1 crop_mask2 = mask2 if img_shape1[0] > img_shape2[0]: if img_shape1[1] >= img_shape2[1]: crop_mask1 = mask1[0:img_shape2[0], 0:img_shape2[1]] crop_mask2 = mask2[0:img_shape2[0], 0:img_shape2[1]] if img_shape1[1] < img_shape2[1]: crop_mask1 = mask1[0:img_shape2[0], 0:img_shape1[1]] crop_mask2 = mask2[0:img_shape2[0], 0:img_shape1[1]] elif img_shape1[0] < img_shape2[0]: if img_shape1[1] >= img_shape2[1]: crop_mask1 = mask1[0:img_shape1[0], 0:img_shape2[1]] crop_mask2 = mask2[0:img_shape1[0], 0:img_shape2[1]] if img_shape1[1] < img_shape2[1]: crop_mask1 = mask1[0:img_shape1[0], 0:img_shape1[1]] crop_mask2 = mask2[0:img_shape1[0], 0:img_shape1[1]] for angle in np.arange(0, 360, angles): myList[int(i)] = imutils.rotate(crop_mask2, angle) i = i + 1 for a in range(len(myList)): differList[a] = cv.subtract(crop_mask1, myList[a]) for b in range(len(myList)): blackPixList[b] = np.sum(differList[b] == 0) orientationValue = ((((mask2List.index(min(mask2List))) * angles) + ((blackPixList.index(max(blackPixList))) * angles)) - 360) - ((mask1List.index(min(mask1List))) * angles) if orientationValue <= (-360): orientationValue = orientationValue + 360 if orientationValue >= 360: orientationValue = orientationValue - 360 print("max ", max(blackPixList), "index ", blackPixList.index(max(blackPixList))) print("orientation :", orientationValue) cv.imwrite('images_temp/mask1.jpg', crop_mask1) cv.imwrite('images_temp/mask2.jpg', crop_mask2) cv.imwrite('images_temp/mask_final.jpg', myList[blackPixList.index(max(blackPixList))])
# to be detected in the HSV color space colorLower = (24, 100, 100) colorUpper = (44, 255, 255) # Start with LED off print("\n Starting..... ==> Press 'q' to quit Program \n") GPIO.output(redLed, GPIO.LOW) ledOn = False # loop over the frames from the video stream while True: # grab the next frame from the video stream, Invert 180o, resize the # frame, and convert it to the HSV color space frame = vs.read() frame = imutils.resize(frame, width=500) frame = imutils.rotate(frame, angle=180) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # construct a mask for the obect color, then perform # a series of dilations and erosions to remove any small # blobs left in the mask mask = cv2.inRange(hsv, colorLower, colorUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # find contours in the mask and initialize the current # (x, y) center of the object cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] center = None
count = 0 print("path:" + path) # loop over the frames of the video while True: # grab the current frame and initialize the occupied/unoccupied # text frame = vs.read() frame = frame if args.get("video", None) is None else frame[1] text = "Emtpy" # if the frame could not be grabbed, then we have reached the end # of the video if frame is None: break # resize the frame, convert it to grayscale, and blur it frame = imutils.resize(frame, width=500) frame = imutils.rotate(frame, 90) # mask mask = np.zeros(frame.shape, dtype=np.uint8) roi_corners = np.array([[(300, 10), (490, 310), (10, 290), (210, 10)]], dtype=np.int32) # fill the ROI so it doesn't get wiped out when the mask is applied channel_count = frame.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255, ) * channel_count cv2.fillPoly(mask, roi_corners, ignore_mask_color) # apply the mask frame = cv2.bitwise_and(frame, mask) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) greenMask = cv2.inRange(hsv, (26, 10, 30), (255, 255, 255))
#Initial run camera print("Staring the camera. Please wait for 2 seconds") vs = VideoStream(0).start() time.sleep(2.0) # Joycon color joyconLower = (99, 100, 100) joyconUpper = (119, 255, 255) while True: sleep(1) print("Grab Frame") tmpFrame = vs.read() tmpFrame = imutils.resize(tmpFrame, width=500) tmpFrame = imutils.rotate(tmpFrame, angle=180) hsv = cv2.cvtColor(tmpFrame, cv2.COLOR_BGR2HSV) print("Create tmpMask") tmpMask = cv2.inRange(hsv, joyconLower, joyconUpper) tmpMask = cv2.erode(tmpMask, None, iterations=2) tmpMask = cv2.dilate(tmpMask, None, iterations=2) print("Find Joycon..") countsCircle = cv2.findContours(tmpMask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) countsCircle = countsCircle[0] if imutils.is_cv4() else countsCircle[1] center = None if len(countsCircle) > 0: print("Find Object")
# keep looping while True: # grab the current frame (grabbed, frame) = camera.read() # if we are viewing a video and we did not grab a frame, # then we have reached the end of the video if args.get("video") and not grabbed: break # resize the frame, blur it, and convert it to the HSV # color space frame = imutils.resize(frame, width=600) if args.get("video"): frame = imutils.rotate(frame, -90) # blurred = cv2.GaussianBlur(frame, (11, 11), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # construct a mask for the color "green", then perform # a series of dilations and erosions to remove any small # blobs left in the mask mask = cv2.inRange(hsv, greenLower, greenUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # find contours in the mask and initialize the current # (x, y) center of the ball cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:balls]