def _symmetric_loss(self, img, box): try: x, y, dx, dy = [int(x) for x in box] if dx % 2 != 0: # odd-length border process dx -= 1 dy -= 1 # left-up, right-up, left-down, right-down rois = [ img[y:y + dy // 2, x:x + dx // 2], img[y:y + dy // 2, x + dx // 2:x + dx], img[y + dy // 2:y + dy, x:x + dx // 2], img[y + dy // 2:y + dy, x + dx // 2:x + dx] ] for i in range(len(rois)): rois[i] = cv.cvtColor(rois[i], cv.COLOR_BGR2GRAY) # normalization rois[i] = (rois[i] / 255.0).astype(np.float64) # check 0 and 3 area loss03 = np.linalg.norm( cv.rotate(rois[0], cv.ROTATE_180).reshape(1, -1) - rois[3].reshape(1, -1)) # check 1 and 2 area loss12 = np.linalg.norm( cv.rotate(rois[1], cv.ROTATE_180).reshape(1, -1) - rois[2].reshape(1, -1)) return 0.5 * (loss12 + loss03) except: return -1
def take_snapshot(cam, bucket, config): if cam is not None and cam.isOpened(): _, frame = cam.read() for transform in config['transformations']: if transform['action'] == 'flip': if transform['axis'] == 'x': frame = cv2.flip(frame, 0) elif transform['axis'] == 'y': frame = cv2.flip(frame, 1) elif transform['axis'] == 'xy': frame = cv2.flip(frame, -1) elif transform['action'] == 'rotate': if transform['direction'] == 'CW90': frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) elif transform['direction'] == 'CCW90': frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE) elif transform['direction'] == '180': frame = cv2.rotate(frame, cv2.ROTATE_180) cv2.imwrite('./{0}.png'.format(bucket), frame) upload_coc('./{0}.png'.format(bucket), bucket) dt = datetime.now() if (dt.hour < dt_range[0]) | (dt.hour > dt_range[1]): ticker = Timer(30.0 * 60.0, take_snapshot, args=[cam, bucket, config]) else: ticker = Timer(config['interval'], take_snapshot, args=[cam, bucket, config]) tickers[config['index']] = ticker ticker.start()
def batch_resize(folder_path, save_path, dst_size=(600, 800)): img_names = os.listdir(folder_path) for i, name in enumerate(img_names): img = cv.imread(folder_path + '/' + name, 1) if img.shape[0] < img.shape[1]: # for "fat" images img = cv.rotate(img, cv.ROTATE_90_CLOCKWISE) img = cv.resize(img, dst_size) cv.imwrite(save_path + '/' + name.split('.')[0] + '.jpg', img) print('{}/{} is resized to {}, current {}, total {}'.format( folder_path, name, dst_size, i + 1, len(img_names))) print('Done!')
def _polar_warp_and_rotate(self, img, ellipse): ''' Take the center of a valve as origin and warp it into x-y plane. @img: np.array, input valve ROI. @ellipse: tuple, it should be the output of the valve detector. @return: np.array, image after polar warping and 90-degree counter-clockwise rotation. ''' center = (int(ellipse[0][0]), int(ellipse[0][1])) self.radius = int(max(ellipse[1]) / 2) mask = np.zeros(img.shape, dtype=np.uint8) mask = cv.circle(mask, center, self.radius, (255, 255, 255), cv.FILLED) img = cv.bitwise_and(mask, img) img = cv.warpPolar(img, (0, 0), center, max(img.shape), cv.WARP_POLAR_LINEAR + cv.WARP_FILL_OUTLIERS) img = cv.rotate(img, cv.ROTATE_90_COUNTERCLOCKWISE) return img
def rotate_image(img_read, rotation): """ Rotates a given image by a given rotation clock wise :parameter img_read: binary image array rotation: Rotation clock wise in degree :returns array of the new rotated image """ if rotation is not None: rotate_value = (str.split(str(rotation), " ")[1]) if isinstance(rotate_value, int) or isinstance(rotate_value, float): value_cw = -float(rotate_value) img_rotated = rotate(img_read, value_cw) return img_rotated else: return img_read else: return img_read
def convert_to_pdf(input_files, output_files, pdf_path, rotation_flag=None, _debug=False): codec = JpegCodec() for i, input_path, output_path in zip(range(len(input_files)), input_files, output_files): with time_ctx("page {}/{}".format(i + 1, len(input_files))): img = codec.imread(input_path) if rotation_flag is not None: img = cv2.rotate(img, rotation_flag) page = extract_page(img, _debug=_debug) codec.imwrite(output_path, page) if _debug: import matplotlib.pyplot as plt plt.show() with time_ctx("pdf"): with open(pdf_path, "wb") as f: f.write(img2pdf.convert(output_files))
def rotate_dataset(dataframe, rotation): ''' arguments: df with cols = ['id', 'loc', 'lab', 'datas'] rotation = cv2.ROTATION_TYPE rotate the picture return df with same columns and image rotated in 'data' ''' print('{}: rotate_dataset function'.format(os.path.basename(__file__))) rots = [] for img in dataframe['datas']: red = img[0] blue = img[1] green = img[2] # convert picture image = cv2.merge((red, blue, green)) # Rotate rot = cv2.rotate(image, rotation) # Get RGB r_rot, g_rot, b_rot = cv2.split(rot) #Save rots.append([r_rot, g_rot, b_rot]) # Convert all into pandas Series rot_series = pd.Series(rots) scene_series = pd.Series(dataframe['id']) loc_series = pd.Series(dataframe['loc']) lab_series = pd.Series(dataframe['lab'], dtype = np.int) # Create DataFrame frame = { 'id': scene_series, 'loc': loc_series, 'lab': lab_series, 'datas':rot_series } df = pd.DataFrame(frame) return df
def retrieve_dipstick_image(image, contour): """ Calculate the minimum area bounding the dipstick image, then apply a rotation matrix to straighten the rectangle. If the dipstick has been rotated into a vertical position it is rotated anticlockwise. The horizontal dipstick image is then resized for extracting squares on the dipstick. """ try: rectangle = cv.minAreaRect(contour) except cv.error: return None center, size, theta = rectangle height, width = image.shape[:2] center, size = tuple(map(int, center)), tuple(map(int, size)) matrix = cv.getRotationMatrix2D(center, theta, 1) dst = cv.warpAffine(image, matrix, (width, height)) dipstick = cv.getRectSubPix(dst, size, center) if dipstick.shape[0] > dipstick.shape[1]: dipstick = cv.rotate(dipstick, cv.ROTATE_90_COUNTERCLOCKWISE) dipstick = imutils.resize(dipstick, width=800) return dipstick
frameList[i] = np.where(variance==np.max(currFrame))[0] if i > 0 and i != K: while frameList[i]-frameList[i-1] <= minDist: currFrame = np.sort(currFrame) currFrame = currFrame[::-1] currFrame = currFrame[1:]; frameList[i] = np.where(variance==currFrame[0])[0] #%% if os.path.exists(outputPath): fileList = [f for f in os.listdir(outputPath)] for f in fileList: os.remove(os.path.join(outputPath,f)) else: os.mkdir(outputPath) cap = cv2.VideoCapture(inputPath) for i in frameList: cap.set(1, int(i)) ret, frame = cap.read() frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) frameName = str('frame_'+ str(int(i))+ '.png') cv2.imwrite(os.path.join(outputPath, frameName), frame) cap.release()
def _main(img): if if_flip: cv2.flip(img, -1, img) # in-place if if_rot: cv2.rotate(img, rot_code, img) return img
mediumThickMask = cv2.cvtColor(mediumThickMask, cv2.COLOR_BGR2GRAY).astype(np.uint8) mediumThickMask = cv2.cvtColor(mediumThickMask, cv2.COLOR_GRAY2BGR).astype(np.uint8) highThickMask = highThickMask & maskrandom2 highThickMask = cv2.cvtColor(highThickMask, cv2.COLOR_BGR2GRAY).astype(np.uint8) highThickMask = cv2.cvtColor(highThickMask, cv2.COLOR_GRAY2BGR).astype(np.uint8) for imgType in imgTypes: original_img = cv2.imread( os.path.join(imgPath + imgPostfix, stoneName + "_" + imgType + imgPostfix + ".bmp")) original_img = cv2.rotate(original_img, cv2.ROTATE_180) original_img = cv2.flip(original_img, 1) result_image = original_img.copy() imgavg = np.array([0, 0, 0]).astype(np.uint8) for i in range(3): imgavg[i] = np.average(original_img[:, :, i]) brightnessRand = np.zeros((imgSize, imgSize, 3)) if (min(imgavg) >= brightnessDisp): brightnessRand[:, :, 0] = np.random.randint(-brightnessDisp, brightnessDisp, (imgSize, imgSize), np.int8) else:
def captureFrame(self, escapeFrame=False): #self.caps = [] # Guardar tlastTime si NO se escapa el frame saveTime = not escapeFrame self.frames = {} self.tlastTime = time.now() if saveTime: self.tlastCapt = self.tlastTime #comprobar cada cierto TIMEOUT la conexión de cámaras self.checkConn() if len(self.cams) == 0: print("No hay cámaras activas configuradas.") for cam in self.cams: if self.camstat[cam["nombre"]][1] == CamStatus.OK: try: #crea captura si no había sido creado if (not cam["nombre"] in self.caps or self.caps[cam["nombre"]] is None): capture = cv2.VideoCapture(cam["url"]) # Prueba de limitar tamano de frame capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640) #3 capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) #4 capture.set(cv2.CAP_PROP_FPS, 30) # FPS esperados self.caps[cam["nombre"]] = capture if (self.caps[cam["nombre"]] and self.caps[cam["nombre"]].isOpened()): ###ret, image_np = self.caps[cam["nombre"]].read() #solicitar frame ret = self.caps[cam["nombre"]].grab() if ret: #renovar estado OK de cámara self.setCamStat(cam["nombre"], CamStatus.OK, "frame") # se puede evitar traer frame si no se hace stream de la camara if True or not escapeFrame: #obtener/recuperar frame solicitado ret, image_np = self.caps[ cam["nombre"]].retrieve() if ret: image_np = cv2.rotate( image_np, rotateCode=cv2.ROTATE_90_CLOCKWISE) self.frames[cam["nombre"]] = image_np else: err = "No se recibió frame: " + cam["nombre"] self.setCamStat(cam["nombre"], CamStatus.ERR_CV2CAP, err) else: err = "No se recibe stream de origen: " + cam["nombre"] self.setCamStat(cam["nombre"], CamStatus.ERR_CV2CAP, err) except IOError as e: err = "Error abriendo socket: " + cam[ "nombre"] + " (" + e + ")" self.setCamStat(cam["nombre"], CamStatus.ERR_SOCKET, err) #print(time.now(), "Error abriendo socket: ", ipcamUrl) except cv2.error as e: err = "Error CV2: " + cam["nombre"] + " (" + e + ")" self.setCamStat(cam["nombre"], CamStatus.ERR_CV2CAP, err) #print(time.now(), "Error CV2: ", e) #else: # Tambien ocurre ante error de usuario / contraseña # print(cam["nombre"], " con error: ",self.camstat[cam["nombre"]], " (compruebe usuario/contraseña)") #No setear nuevo estado: self.setCamStat(cam["nombre"], CamStatus.ERR_, err) return self.frames
def main(): # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name video_path = "videos/VIRB0407.MP4" # cap = cv2.VideoCapture("videos/VIRB0392.MP4") # cap.set(1, 700) cap = cv2.VideoCapture(video_path) cap.set(1, 300) frame_width = int(cap.get(3)) frame_height = int(cap.get(4)) # codec = cv2.VideoWriter_fourcc(*"DIVX") # fps = 30 # out = cv2.VideoWriter("output.avi", 0, fps, (frame_width, frame_height)) k = None frame_number = 0 detect = Darknet() retrieve = RetrieveClass() rectify = RectifyClass(retrieve) face_detection = FaceDetectionClass() localize = LocalizeClass() # Check the extension of video, MOV files are rotated by -90° file_name, file_extension = os.path.splitext(video_path) # Check if camera opened successfully if cap.isOpened() == False: print("Error opening video stream or file") # Read until video is completed while cap.isOpened(): ret, frame = cap.read() if ret == True: frame_number += 1 print(f'############ FRAME N° {frame_number} ############') if file_extension.upper() == ".MOV": frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) # bb_frame is used for drawing, frame is clean bb_frame = frame.copy() detections_list = detect.yolo_detection(bb_frame) # show_img("Frame with detections", bb_frame) for detection in detections_list: if detection[0] == 'painting' and not is_roi_outside_frame( frame_width, frame_height, *detection[2:6]): left = detection[2] # x top = detection[3] # y right = detection[4] # x + w bottom = detection[5] # y + h painting = frame[int(top):int(bottom), int(left):int(right)] print("[INFO] Painting detected") rectify.rectify(painting) if detection[0] == 'painting' and len(detections_list) == 1: # It founds only one painting, the roi can be outside frame left = max(0, detection[2]) # x top = max(0, detection[3]) # y right = min(detection[4], frame_height) # x + w bottom = min(detection[5], frame_width) # y + h painting = frame[int(top):int(bottom), int(left):int(right)] print("[INFO] Painting detected") rectify.rectify(painting) elif detection[0] == 'person': # FACE DETECTION left = detection[2] right = detection[4] top = detection[3] bottom = detection[5] # TO DO AGGIUSTARE IL ROI print("[INFO] Person detected") person_roi = frame[int(top * 1.3):int(bottom), left:right] if not face_detection.is_facing_camera(person_roi, True): paintings_detections = [ element for element in detections_list if element[0] == 'painting' ] if face_detection.is_facing_paintings( detection, paintings_detections): paintings_detections = [ element for element in detections_list if element[0] == 'painting' ] for painting in paintings_detections: left_p = painting[2] right_p = painting[4] top_p = painting[3] bottom_p = painting[5] if not is_roi_outside_frame( frame_width, frame_height, * painting[2:6]): painting_roi = frame[ int(top_p):int(bottom_p), int(left_p):int(right_p)] try: ranked_list, dst_points, src_points = retrieve.retrieve( painting_roi) localize.localize(ranked_list) except TypeError: print( "[ERROR] Can't localize the person" ) cv2.rectangle(bb_frame, (left, bottom + 10), (left + 50, bottom + 10), (255, 255, 255)) elif detection[0] == 'statue': print("[INFO] Statue detected") # Break the loop else: break # When everything done, release the video capture and writer objects cap.release() # Closes all the frames cv2.destroyAllWindows()
from cv2 import cv2 img = cv2.imread('HQ66W2S.jpg') img_rotate_90_clockwise = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) print(img) print("shape : ", img.shape) for i in img: for j in i: j[1] = 0 j[2] = 0 cv2.imshow('Test Image', img_rotate_90_clockwise) cv2.waitKey(0) cv2.destroyAllWindows()
1, math.pi / 180, 100, minLineLength=100, maxLineGap=10) (x, y, w, h) = (np.amin(img_hough, axis=0)[0, 0], np.amin(img_hough, axis=0)[0, 1], np.amax(img_hough, axis=0)[0, 0] - np.amin(img_hough, axis=0)[0, 0], np.amax(img_hough, axis=0)[0, 1] - np.amin(img_hough, axis=0)[0, 1]) img_roi = img_copy[y:y + h, x:x + w] ##################################### img_roi = cv2.rotate(img_roi, cv2.ROTATE_90_COUNTERCLOCKWISE) (height, width) = img_roi.shape img_roi_copy = img_roi.copy() dim_mrz = (x, y, w, h) = (1, round(height * 0.9), width - 3, round(height - (height * 0.9)) - 2) img_roi_copy = cv2.rectangle(img_roi_copy, (x, y), (x + w, y + h), (0, 0, 0), 2) img_mrz = img_roi[y:y + h, x:x + w] img_mrz = cv2.GaussianBlur(img_mrz, (3, 3), 0) ret, img_mrz = cv2.threshold(img_mrz, 127, 255, cv2.THRESH_TOZERO) mrz = pytesseract.image_to_string(img_mrz, config='--psm 12') mrz = [line for line in mrz.split('\n') if len(line) > 10]
def load_dataset(dataset_path): ''' Load all files from path parameter Get labels, scenes ID and locations of each picture Convert pictures PNG into RGB Save image, rotate image and image with birghtness increased return numpy array of : labels (1D), scenes_id (1D), locations (2d), images numpy array( [nb_picutres,RGB,witdh,length]), turned image (rotations) numpy array( [nb_picutres,RGB,witdh,length]), images with more brightness (hsv_array) numpy array( [nb_picutres,RGB,witdh,length]) ''' print('{}: load_dataset function'.format(os.path.basename(__file__))) #Get all files into the path dirfiles = os.listdir(dataset_path) # Init lists # labels labs = [] # Scenes ID ids = [] # Location locs = [] # Pictures in RGB imgs = [] # Rotate pictures in RGB rots = [] # Values of HSV modify hsvs = [] first = True for file in tqdm(os.listdir(dataset_path)): # Get all information with name of file label,scene_id, coord = file.split('__') # Split longitude, latitude & delete '.png' longitude, latitude = coord[:-4].split('_') # Save into list labs.append(label) ids.append(scene_id) locs.append([longitude, latitude]) # Get image path img_path = os.path.join(dataset_path, file) # Convert image img = cv2.imread(img_path) # BGR -> RGB img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # ------------------------------------------------- ## 1. Save normal picture # Get RGB red, green, blue = cv2.split(img) # Save picture imgs.append([red,green,blue]) # ------------------------------------------------- ## 2. Modify picture with HSV value # Increase brightness img_hsv = increase_brightness(img, value = 20) # Split r_hsv, g_hsv, b_hsv = cv2.split(img_hsv) # Save hsvs.append([r_hsv, g_hsv, b_hsv]) # ------------------------------------------------- ## 3. Rotate picture # Rotation rot = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) # Get RGB r_rot, g_rot, b_rot = cv2.split(rot) #Save rots.append([r_rot, g_rot, b_rot]) # Convert list to Series labels = np.array(labs,dtype = np.int) scenes_id = np.array(ids) locations = np.array(locs) images = np.array(imgs,dtype=np.int) rotations = np.array(rots,dtype=np.int) hsv_array = np.array(hsvs, dtype = np.int) return labels, scenes_id, locations, images, rotations, hsv_array
def thread_aug_data_function(self, data_fragment, root_orig_path, root_segm_path): for n, id_ in tqdm(enumerate(data_fragment), total=len(data_fragment)): # print(DST_PARENT_DIR + ORIGINAL_RESIZED_PATH + id_) original_img = imread(root_orig_path + id_)[:, :, :IMG_CHANNELS] segmented_img = imread(root_segm_path + id_)[:, :, :IMG_CHANNELS] aug_originals = [] aug_segmented = [] # roatated images rot_o_90 = cv2.rotate(original_img, cv2.ROTATE_90_CLOCKWISE) aug_originals.append(rot_o_90) rot_o_180 = cv2.rotate(original_img, cv2.ROTATE_180) aug_originals.append(rot_o_180) rot_o_270 = cv2.rotate(original_img, cv2.ROTATE_90_COUNTERCLOCKWISE) aug_originals.append(rot_o_270) # horizontally flipped images flip_o_h_org = cv2.flip(original_img, 1) aug_originals.append(flip_o_h_org) flip_o_h_90 = cv2.flip(rot_o_90, 1) aug_originals.append(flip_o_h_90) flip_o_h_180 = cv2.flip(rot_o_180, 1) aug_originals.append(flip_o_h_180) flip_o_h_270 = cv2.flip(rot_o_270, 1) aug_originals.append(flip_o_h_270) # brighter images brighter_o_ = cv2.add(original_img, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_) brighter_o_rot_o_90 = cv2.add( rot_o_90, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_rot_o_90) brighter_o_rot_o_180 = cv2.add( rot_o_180, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_rot_o_180) brighter_o_rot_o_270 = cv2.add( rot_o_270, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_rot_o_270) brighter_o_flip_o_h_org = cv2.add( flip_o_h_org, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_flip_o_h_org) brighter_o_flip_o_h_90 = cv2.add( flip_o_h_90, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_flip_o_h_90) brighter_o_flip_o_h_180 = cv2.add( flip_o_h_180, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_flip_o_h_180) brighter_o_flip_o_h_270 = cv2.add( flip_o_h_270, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(brighter_o_flip_o_h_270) # dimmer images dimmer_o_ = cv2.subtract(original_img, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_) dimmer_o_rot_o_90 = cv2.subtract( rot_o_90, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_rot_o_90) dimmer_o_rot_o_180 = cv2.subtract( rot_o_180, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_rot_o_180) dimmer_o_rot_o_270 = cv2.subtract( rot_o_270, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_rot_o_270) dimmer_o_flip_o_h_org = cv2.subtract( flip_o_h_org, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_flip_o_h_org) dimmer_o_flip_o_h_90 = cv2.subtract( flip_o_h_90, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_flip_o_h_90) dimmer_o_flip_o_h_180 = cv2.subtract( flip_o_h_180, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_flip_o_h_180) dimmer_o_flip_o_h_270 = cv2.subtract( flip_o_h_270, np.array([random.randint(50, 80) / 1.0])) aug_originals.append(dimmer_o_flip_o_h_270) # same operations for segmented data rot_s_90 = cv2.rotate(segmented_img, cv2.ROTATE_90_CLOCKWISE) aug_segmented.append(rot_s_90) rot_s_180 = cv2.rotate(segmented_img, cv2.ROTATE_180) aug_segmented.append(rot_s_180) rot_s_270 = cv2.rotate(segmented_img, cv2.ROTATE_90_COUNTERCLOCKWISE) aug_segmented.append(rot_s_270) flip_s_h_org = cv2.flip(segmented_img, 1) aug_segmented.append(flip_s_h_org) flip_s_h_90 = cv2.flip(rot_s_90, 1) aug_segmented.append(flip_s_h_90) flip_s_h_180 = cv2.flip(rot_s_180, 1) aug_segmented.append(flip_s_h_180) flip_s_h_270 = cv2.flip(rot_s_270, 1) aug_segmented.append(flip_s_h_270) # brighter segmented images aug_segmented.append(segmented_img.copy()) aug_segmented.append(rot_s_90.copy()) aug_segmented.append(rot_s_180.copy()) aug_segmented.append(rot_s_270.copy()) aug_segmented.append(flip_s_h_org.copy()) aug_segmented.append(flip_s_h_90.copy()) aug_segmented.append(flip_s_h_180.copy()) aug_segmented.append(flip_s_h_270.copy()) # dimmer segmented images aug_segmented.append(segmented_img.copy()) aug_segmented.append(rot_s_90.copy()) aug_segmented.append(rot_s_180.copy()) aug_segmented.append(rot_s_270.copy()) aug_segmented.append(flip_s_h_org.copy()) aug_segmented.append(flip_s_h_90.copy()) aug_segmented.append(flip_s_h_180.copy()) aug_segmented.append(flip_s_h_270.copy()) for i in range(0, len(aug_segmented)): # saves all the augmented originals rgb_orig = cv2.cvtColor(aug_originals[i], cv2.COLOR_BGR2RGB) cv2.imwrite( root_orig_path + id_.split('.')[0] + '_' + str( (i + 1)) + '.png', rgb_orig) # saves all the augmented segmented rgb_segm = cv2.cvtColor(aug_segmented[i], cv2.COLOR_BGR2RGB) cv2.imwrite( root_segm_path + id_.split('.')[0] + '_' + str( (i + 1)) + '.png', rgb_segm) pass
# matrice di rotazione M = cv2.getRotationMatrix2D(center, 45, 1.0) # trasformazione affine rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("rotated by 45°", rotated) cv2.waitKey() # trasformazione affine M = cv2.getRotationMatrix2D(center, 90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("rotated by 90°", rotated) cv2.waitKey() def rotateBy(image, angle, center=None, scale=1.0): h, w = image.shape[:2] if not center: center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, scale) return cv2.warpAffine(image, M, (w, h)) cv2.imshow("rotated by 180°", rotateBy(image, 180)) cv2.waitKey() # la rotazione cv2 built-in è limitata a 90 e 180 rotated = cv2.rotate(image, cv2.ROTATE_180) cv2.imshow("built-in func", rotated) cv2.waitKey()
frames = [] # Get frame for i, c in enumerate(cap): success, fr = c.read() fr = cv2.resize(fr, wantShape) if success: frames.append(fr) else: frames.append( np.zeros((globalSize[1], globalSize[0], 3), dtype=np.uint8)) print("Error reading camera from {i}".format(i=i)) # Rotate Specified frame for ne in needToRotate: frames[ne] = cv2.rotate(frames[ne], cv2.ROTATE_90_COUNTERCLOCKWISE) # frame[ne] = cv2.resize(frame[ne], globalSize) # Write frame to file for i, w in enumerate(writers): w.write(frames[i]) cv2.putText(frames[i], "Recording", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) # Show the frame for f in range(0, len(frames)): cv2.imshow("frame" + str(f), frames[f]) # keyborad handler with opencv key = cv2.waitKey(1) & 0xFF if key == ord('q'):
from matplotlib import pyplot # 水平翻轉 img1 = cv2.imread('test1.jpg') flip_1 = cv2.flip(img1, 1) cv2.imshow('test1_flip1.jpg', flip_1) # 垂直翻轉 flip_2 = cv2.flip(img1, 0) cv2.imshow('test1_flip2.jpg', flip_2) # 水平+垂直翻轉 flip_3 = cv2.flip(img1, 1) cv2.imshow('test1_flip3.jpg', flip_3) # 90度旋轉 img2 = cv2.imread('test2.jpg') rotate_1 = cv2.rotate(img2, cv2.ROTATE_90_CLOCKWISE) cv2.imshow('test1_rotate90.jpg', rotate_1) # 180度旋轉 rotate_2 = cv2.rotate(img2, cv2.ROTATE_180) cv2.imshow('test1_rotate180.jpg', rotate_2) # 270度旋轉 rotate_3 = cv2.rotate(img2, cv2.ROTATE_90_COUNTERCLOCKWISE) cv2.imshow('test1_rotate270.jpg', rotate_3) img3 =cv2.imread('test3.jpg') crop_1=img3[0:240,0:426] cv2.imshow('test1_crop_1.jpg',crop_1) img3 =cv2.imread('test3.jpg') crop_2=img3[240:480,426:852] cv2.imshow('test1_crop_2.jpg',crop_2)