实习内容

代码

# -*- coding:utf-8 -*-
# 背景检测
import cv2

# 这里修改要检测图像的路径
img = cv2.imread('C:/Users/simao.wang.HIRAIN/Desktop/test05.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


def mouse_click(event, x, y, flags, para):
    if event == cv2.EVENT_LBUTTONDOWN:  # 左边鼠标点击
        # print('PIX:', x, y)
        print("BGR:", img[y, x])
        print("GRAY:", gray[y, x])
        # print("HSV:", hsv[y, x])


if __name__ == '__main__':
    cv2.namedWindow("img")
    cv2.setMouseCallback("img", mouse_click)
    while True:
        cv2.imshow('img', img)
        if cv2.waitKey() == ord('q'):
            break
    cv2.destroyAllWindows()

#模板匹配和背景灯检测——原始
import cv2
import numpy as np


print(cv2.__version__)  # 3.4.2

# 1.模板匹配
#这里是输入的目标图像
img = cv2.imread('C:/Users/simao.wang.HIRAIN/Desktop/task01.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换为灰度图
print(img_gray.shape)  # 显示目标大小

#这里是输入的模板图像
template = cv2.imread('C:/Users/simao.wang.HIRAIN/Desktop/task01-1.jpg', 0)
print(template.shape)  # 显示模板大小
h, w = template.shape[:2]  # rows->h, cols->w

# 6种匹配方法
# methods = [cv2.TM_CCOEFF,  相关匹配
#            cv2.TM_CCOEFF_NORMED,  标准相关匹配
#            cv2.TM_CCORR,
#            cv2.TM_CCORR_NORMED,
#            cv2.TM_SQDIFF,
#            cv2.TM_SQDIFF_NORMED]
#相似度度量指标
# 差值平方和匹配 CV_TM_SQDIFF 原理:计算模板与某个子图的对应像素的差值平方和。越相似该值越小
# 标准化差值平方和匹配 CV_TM_SQDIFF_NORMED 原理:这种标准化操作可以保证当模板和图像各个像素的亮度都乘上了同一个系数时,相关度不发生变化。越相似该值越小
# 相关匹配 CV_TM_CCORR 原理:模板与子图对应位置相乘,可以将其看作是差值平方和平方项展开之后中间的那个2ab项。越相似该值越大
# 标准相关匹配 CV_TM_CCORR_NORMED 原理:和标准化差值平方和匹配类似,都是去除了亮度线性变化对相似度计算的影响。可以保证图像和模板同时变亮或变暗k倍时结果不变。越相似该值越大
# 相关匹配 CV_TM_CCOEFF 原理:把图像和模板都减去了各自的平均值,使得这两幅图像都没有直流分量。越相似该值越大
# 标准相关匹配 CV_TM_CCOEFF_NORMED 原理:在减去了各自的平均值之外,还要各自除以各自的方差。经过减去平均值和除以方差这么两步操作之后,无论是我们的目标图像还是模板都被标准化了,这样可以保证图像和模板分别改变光照不影响计算结果。越相似该值越大

#这里选取了两种算法作为模板匹配的方法
methods = [cv2.TM_CCOEFF_NORMED,
           cv2.TM_SQDIFF_NORMED]

for meth in methods:
    img2 = img.copy()

    res = cv2.matchTemplate(img_gray, template, meth) #求出模板与目标图像匹配得到的矩阵结果
    print(res.shape) #矩阵的大小

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) #求出这个矩阵的最小值,最大值,并得到最大值,最小值的索引

    # 如果是平方差匹配TM_SQDIFF或归一化平方差匹配TM_SQDIFF_NORMED,取最小值
    if meth in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc

    bottom_right = (top_left[0] + w, top_left[1] + h) #画框的右下坐标

    #显示出模板中心点的灰度值,用于检测背景灯的亮度读数
    x=int(top_left[0] + w/2) #模板中心点的x坐标
    y=int(top_left[1] + h/2) #模板中心点的y坐标
    print(x,y) #模板中心点坐标
    print("GRAY:", img_gray[y, x]) #模板中心点的灰度值

    # 在匹配点即模板左上角画小圆心
    cv2.circle(res, top_left, 10, 0, 2)
    cv2.namedWindow('res',cv2.WINDOW_FREERATIO)
    cv2.imshow("res", res)

    # 画矩形,框出模板在目标图像中的位置
    cv2.rectangle(img2, top_left, bottom_right, (0, 255, 0), 2)
    cv2.namedWindow('img2', cv2.WINDOW_FREERATIO)
    cv2.imshow("img2", img2)
    cv2.waitKey(0)

#相似度度量指标
# 差值平方和匹配 CV_TM_SQDIFF 原理:计算模板与某个子图的对应像素的差值平方和。越相似该值越小
# 标准化差值平方和匹配 CV_TM_SQDIFF_NORMED 原理:这种标准化操作可以保证当模板和图像各个像素的亮度都乘上了同一个系数时,相关度不发生变化。越相似该值越小
# 相关匹配 CV_TM_CCORR 原理:模板与子图对应位置相乘,可以将其看作是差值平方和平方项展开之后中间的那个2ab项。越相似该值越大
# 标准相关匹配 CV_TM_CCORR_NORMED 原理:和标准化差值平方和匹配类似,都是去除了亮度线性变化对相似度计算的影响。可以保证图像和模板同时变亮或变暗k倍时结果不变。越相似该值越大
# 相关匹配 CV_TM_CCOEFF 原理:把图像和模板都减去了各自的平均值,使得这两幅图像都没有直流分量。越相似该值越大
# 标准相关匹配 CV_TM_CCOEFF_NORMED 原理:在减去了各自的平均值之外,还要各自除以各自的方差。经过减去平均值和除以方差这么两步操作之后,无论是我们的目标图像还是模板都被标准化了,这样可以保证图像和模板分别改变光照不影响计算结果。越相似该值越大
# 基于FLANN的匹配器(FLANN based Matcher)定位图片,只有opencv版本低于3.4.2.16才能使用SIFT特征点匹配方法
import numpy as np
import cv2
from matplotlib import pyplot as plt

MIN_MATCH_COUNT = 7  # 设置最低特征点匹配数量为7,如果找到的特征点数大于这个值,那么就匹配成功并框出在目标图像上匹配到的模板位置
template = cv2.imread('C:/Users/simao.wang.HIRAIN/Desktop/Demotemp.jpg', 0)  # 模板图像,需要人为输入
target = cv2.imread('C:/Users/simao.wang.HIRAIN/Desktop/Demo.jpg', 0)  # 输入的目标图像,目的是为了找到模板图像在目标图像中的位置
# 创建sift(尺度不变特征变换匹配算法)检测器
sift = cv2.xfeatures2d.SIFT_create()
# 在模板图像和目标图像中分别提取特征点
kp1, des1 = sift.detectAndCompute(template, None)
kp2, des2 = sift.detectAndCompute(target, None)
# 创建设置FLANN快速最近邻逼近搜索匹配
# KDtree建立索引方式的常量参数
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50) #checks指定索引树要被遍历的次数为50
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2) #进行匹配搜索
# 寻找距离近的特征点放入列表
good = []
for m, n in matches:
    if m.distance < 0.7 * n.distance:
        good.append(m)
if len(good) > MIN_MATCH_COUNT:
    # 获取关键点的坐标
    src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
    # 计算变换矩阵和MASK
    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
    matchesMask = mask.ravel().tolist()
    h, w = template.shape
    # 使用得到的变换矩阵对原图像的四个角进行变换,获得在目标图像上对应的坐标
    pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
    dst = cv2.perspectiveTransform(pts, M)
    cv2.polylines(target, [np.int32(dst)], True, 0, 2, cv2.LINE_AA)
else:
    print("Not enough matches are found - %d/%d" % (len(good), MIN_MATCH_COUNT))
    matchesMask = None
draw_params = dict(matchColor=(0, 255, 0),
                   singlePointColor=None,
                   matchesMask=matchesMask,
                   flags=2)
result = cv2.drawMatches(template, kp1, target, kp2, good, None, **draw_params)
plt.imshow(result, 'gray')
plt.show()

#SIFT原理:
# 1.通过一个变化尺度的高斯函数对图像进行尺度空间变换,小尺度对应于图像的细节特征,大尺度对应于图像的概貌特征(尺度空间)
# 2.建立高斯图像金字塔和DOG高斯差分金字塔。可以通过高斯差分图像(DOG在计算上只需相邻高斯平滑后图像相减)看出图像上的像素值变化情况。(如果没有变化,也就没有特征。特征必须是变化尽可能多的点。)DOG图像描绘的是目标的轮廓。
# 3.局部极值检测。中间的检测点和它同尺度的8个相邻点和上下相邻尺度对应的9×2个 点共26个点比较,以确保在尺度空间和二维图像空间都检测到极值点。
# 4.去除边缘效应,实现关键的的精确定位
# 5.关键点主方向分配  关键点主方向分配就是基于图像局部的梯度方向,分配给每个关键点位置一个或多个方向。所有后面的对图像数据的操作都相对于关键点的方向、尺度和位置进行变换,使得描述符具有旋转不变性。
# 6.用一组向量描述关键点的特征,每一个关键点,拥有三个信息:位置、尺度以及方向
# 7.利用欧氏距离算出模板和目标图像之间的特征关键点距离,距离越小说明相似度越高。关键点匹配采用Kd树(平衡二叉树)来完成搜索,以目标图像的关键点为基准,搜索与目标图像的特征点最邻近的原图像特征点和次邻近的原图像特征点
# 指针读数
import cv2
import numpy as np


def avg_circles(circles, b):
    avg_x = 0
    avg_y = 0
    avg_r = 0
    for i in range(b):
        # optional - average for multiple circles (can happen when a gauge is at a slight angle)
        avg_x = avg_x + circles[0][i][0]
        avg_y = avg_y + circles[0][i][1]
        avg_r = avg_r + circles[0][i][2]
    avg_x = int(avg_x / (b))
    avg_y = int(avg_y / (b))
    avg_r = int(avg_r / (b))
    return avg_x, avg_y, avg_r


def dist_2_pts(x1, y1, x2, y2):
    return np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)


def calibrate_gauge(gauge_number, file_type,img):
    '''
        This function should be run using a test image in order to calibrate the range available to the dial as well as the
        units.  It works by first finding the center point and radius of the gauge.  Then it draws lines at hard coded intervals
        (separation) in degrees.  It then prompts the user to enter position in degrees of the lowest possible value of the gauge,
        as well as the starting value (which is probably zero in most cases but it won't assume that).  It will then ask for the
        position in degrees of the largest possible value of the gauge. Finally, it will ask for the units.  This assumes that
        the gauge is linear (as most probably are).
        It will return the min value with angle in degrees (as a tuple), the max value with angle in degree45s (as a tuple),
        and the units (as a string).
        这个函数用测试图片来校准刻度盘和刻度盘可用的范围单位。需要之前所得的中心点以及半径。然后绘制出刻度。
        需要输入表盘读数最小角度,最大角度,最小值,最大值,以及单位(min_angle,max_angle,min_value,max_value,units)
    '''
    height, width = img.shape[:2]
    # 将图片转为灰度图片
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # convert to gray

    # 霍夫圆环检测
    # image:8位,单通道图像
    # method:定义检测图像中圆的方法。目前唯一实现的方法cv2.HOUGH_GRADIENT。

    # dp:累加器分辨率与图像分辨率的反比。dp获取越大,累加器数组越小。
    # minDist:检测到的圆的中心,(x,y)坐标之间的最小距离。如果minDist太小,则可能导致检测到多个相邻的圆。如果minDist太大,则可能导致很多圆检测不到。
    # param1:用于处理边缘检测的梯度值方法。
    # param2:cv2.HOUGH_GRADIENT方法的累加器阈值。阈值越小,检测到的圈子越多。
    # minRadius:半径的最小大小(以像素为单位)。
    # maxRadius:半径的最大大小(以像素为单位)。

    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, np.array([]), 100, 50, int(height * 0.4),
                               int(height * 0.5))

    a, b, c = circles.shape
    # 获取圆的坐标x,y和半径r
    x, y, r = avg_circles(circles, b)

    cv2.circle(img, (x, y), r, (0, 0, 255), 3, cv2.LINE_AA)  # 用红色画圆
    cv2.circle(img, (x, y), 2, (0, 255, 0), 3, cv2.LINE_AA)  # 画圆心

    # for testing, output circles on image
    # cv2.imwrite('gauge-%s-circles.%s' % (gauge_number, file_type), img)

    # for calibration, plot lines from center going out at every 10 degrees and add marker
    # for i from 0 to 36 (every 10 deg)

    '''
    goes through the motion of a circle and sets x and y values based on the set separation spacing.  Also adds text to each
    line.  These lines and text labels serve as the reference point for the user to enter
    NOTE: by default this approach sets 0/360 to be the +x axis (if the image has a cartesian grid in the middle), the addition
    (i+9) in the text offset rotates the labels by 90 degrees so 0/360 is at the bottom (-y in cartesian).  So this assumes the
    gauge is aligned in the image, but it can be adjusted by changing the value of 9 to something else.
    根据画出的刻度值,给定x,y的值,并在此位置添加文本信息。
    这些刻度和文本标签用作用户输入的参考点

    '''
    separation = 5.0  # 每格刻度的度数值
    interval = int(360 / separation)
    p1 = np.zeros((interval, 2))  # set empty arrays
    p2 = np.zeros((interval, 2))
    p_text = np.zeros((interval, 2))
    for i in range(0, interval):
        for j in range(0, 2):
            if (j % 2 == 0):
                p1[i][j] = x + 0.9 * r * np.cos(separation * i * 3.14 / 180)  # point for lines
            else:
                p1[i][j] = y + 0.9 * r * np.sin(separation * i * 3.14 / 180)
    text_offset_x = 10
    text_offset_y = 5
    for i in range(0, interval):
        for j in range(0, 2):
            if (j % 2 == 0):
                p2[i][j] = x + r * np.cos(separation * i * 3.14 / 180)
                p_text[i][j] = x - text_offset_x + 1.2 * r * np.cos(
                    (separation) * (i + 9) * 3.14 / 180)  # point for text labels, i+9 rotates the labels by 90 degrees
            else:
                p2[i][j] = y + r * np.sin(separation * i * 3.14 / 180)
                p_text[i][j] = y + text_offset_y + 1.2 * r * np.sin(
                    (separation) * (i + 9) * 3.14 / 180)  # point for text labels, i+9 rotates the labels by 90 degrees

    # 在圆上添加刻度标志
    for i in range(0, interval):
        cv2.line(img, (int(p1[i][0]), int(p1[i][1])), (int(p2[i][0]), int(p2[i][1])), (0, 255, 0), 2)
        cv2.putText(img, '%s' % (int(i * separation)), (int(p_text[i][0]), int(p_text[i][1])), cv2.FONT_HERSHEY_SIMPLEX,
                    0.3, (0, 0, 0), 1, cv2.LINE_AA)

    cv2.imwrite(
        'D:/zhizhendushu/test-%s-calibration.%s' % (
        gauge_number, file_type), img)

    # 手动输入初始信息
    print('gauge number: %s' % gauge_number)
    min_angle = input('Min angle (lowest possible angle of dial) - in degrees: ')  # 圆形仪表最小刻度值
    max_angle = input('Max angle (highest possible angle) - in degrees: ')  # 圆形仪表最大刻度值
    min_value = input('Min value: ')  # 量程最小范围值
    max_value = input('Max value: ')  # 量程最大范围值
    units = input('Enter units: ')

    return min_angle, max_angle, min_value, max_value, units, x, y, r #返回最小刻度,最大刻度,量程最小值,量程最大值,单位,圆形的x坐标,Y坐标,半径


def get_current_value(img, min_angle, max_angle, min_value, max_value, x, y, r, gauge_number, file_type):
    gray2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #先将BGR图像转换成灰度图

    edges = cv2.Canny(gray2, 50, 150, apertureSize=3) #将灰度图进行边缘检测

    # find lines
    minLineLength = 100 #检测直线最短阈值
    maxLineGap = 5
    lines = cv2.HoughLinesP(image=edges, rho=1, theta=np.pi / 180, threshold=100, minLineLength=minLineLength,
                            maxLineGap=maxLineGap)  #霍夫曼直线检测

    print('lines', lines)
    final_line_list = []

    diff1LowerBound = 0.3  #直线起点距离圆心的最小相对位置的最小比例
    diff1UpperBound = 0.5  #直线起点距离圆心的最小相对位置的最大比例
    diff2LowerBound = 0.5  # diff2LowerBound and diff2UpperBound determine how close the other point of the line should be to the outside of the gauge
    diff2UpperBound = 1.0
    for i in range(0, len(lines)):
        for x1, y1, x2, y2 in lines[i]:
            diff1 = dist_2_pts(x, y, x1, y1)  # x, y is center of circle
            diff2 = dist_2_pts(x, y, x2, y2)  # x, y is center of circle
            # set diff1 to be the smaller (closest to the center) of the two), makes the math easier
            if (diff1 > diff2):
                temp = diff1
                diff1 = diff2
                diff2 = temp

            if (((diff1 < diff1UpperBound * r) and (diff1 > diff1LowerBound * r) and (
                    diff2 < diff2UpperBound * r)) and (diff2 > diff2LowerBound * r)):
                print('diff1UpperBound*r', diff1UpperBound * r)
                print('diff1LowerBound*r', diff1LowerBound * r)
                print('diff2UpperBound*r', diff2UpperBound * r)
                print('diff2LowerBound*r', diff2LowerBound * r)
                print('diff1', diff1)
                print('diff2', diff2)
                line_length = dist_2_pts(x1, y1, x2, y2)
                print([x1, y1, x2, y2])
                final_line_list.append([x1, y1, x2, y2]) #将检测出的直线数据放入final_line_list数组中,如果有多根指针需要检测就需要依次遍历

    print(final_line_list)
    x1 = final_line_list[0][0]
    y1 = final_line_list[0][1]
    x2 = final_line_list[0][2]
    y2 = final_line_list[0][3]
    cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) #画出检测到的直线

    # find the farthest point from the center to be what is used to determine the angle
    dist_pt_0 = dist_2_pts(x, y, x1, y1)
    dist_pt_1 = dist_2_pts(x, y, x2, y2)
    if (dist_pt_0 > dist_pt_1):
        x_angle = x1 - x
        y_angle = y - y1
    else:
        x_angle = x2 - x
        y_angle = y - y2
    # take the arc tan of y/x to find the angle
    res = np.arctan(np.divide(float(y_angle), float(x_angle)))

    # these were determined by trial and error
    res = np.rad2deg(res)
    if x_angle > 0 and y_angle > 0:  # in quadrant I
        final_angle = 270 - res
    if x_angle < 0 and y_angle > 0:  # in quadrant II
        final_angle = 90 - res
    if x_angle < 0 and y_angle < 0:  # in quadrant III
        final_angle = 90 - res
    if x_angle > 0 and y_angle < 0:  # in quadrant IV
        final_angle = 270 - res

    # print final_angle

    old_min = float(min_angle)
    old_max = float(max_angle)

    new_min = float(min_value)
    new_max = float(max_value)

    old_value = final_angle

    old_range = (old_max - old_min)
    new_range = (new_max - new_min)
    new_value = (((old_value - old_min) * new_range) / old_range) + new_min #计算指针读数

    return new_value


def main():
    gauge_number = 1
    file_type = 'jpg'
    img = cv2.imread('D:/zhizhendushu/test-%s.%s' % (gauge_number, file_type)) #这里填写目标图像的位置,取名时要在后面加-指针数,但填地址时不用加-后面的,且将画了刻度盘的图存在D盘的zhizhendushu文件夹中
    # name the calibration image of your gauge 'gauge-#.jpg', for example 'gauge-5.jpg'.  It's written this way so you can easily try multiple images
    min_angle, max_angle, min_value, max_value, units, x, y, r = calibrate_gauge(gauge_number, file_type,img) #这里可以改输入图片

    print('min_angle=', min_angle)
    print('max_angle=', max_angle)
    print('min_value=', min_value)
    print('max_value=', max_value)
    print('units=', units)
    print('x=', x)
    print('y=', y)
    print('r=', r)

    print()
    val = get_current_value(img, min_angle, max_angle, min_value, max_value, x, y, r, gauge_number, file_type)
    print("Current reading: %s %s" % (val, units))


if __name__ == '__main__':
    main()

#分割图片
import cv2 as cv
import numpy as np

def conter_demo(image):
    dst=cv.GaussianBlur(image,(3,3),0)
    gray=cv.cvtColor(dst,cv.COLOR_BGR2GRAY)
    cv.imshow("gray", gray)
    ret,binary=cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary",binary)
    dst=cv.cvtColor(binary,cv.COLOR_GRAY2BGR)
    kernel=cv.getStructuringElement(cv.MORPH_RECT,(3,3))
    dilate_binary=cv.dilate(binary,kernel)
    clonImage,contouers,hes=cv.findContours(dilate_binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    for i ,contour in enumerate(contouers):
        x,y,w,h=cv.boundingRect(contour)
        cv.drawContours(image,contouers,i,(0,0,255),-1)
        cv.rectangle(dst,(x,y),(x+w,y+h),(0,0,255),2)
        approxcurve=cv.approxPolyDP(contour,4,True)
        print(x+w/2,y+h/2,i)
    cv.imshow("dst", dst)


src=cv.imread("D:/task01.jpg")
cv.namedWindow("input",cv.WINDOW_AUTOSIZE)
cv.imshow("input",src)
conter_demo(src)
cv.waitKey(0)
# -*- coding: utf-8 -*-
#work_main
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from work.work01 import Ui_MainWindow


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)


#运行的Main文件,运行这个就可以了
if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    myWin.show()
    sys.exit(app.exec_())

#work_label
from PyQt5.QtWidgets import QWidget, QApplication, QLabel
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication
import cv2


# 自定义的Label类
class MyLabel(QLabel):
    x0 = 0
    y0 = 0
    x1 = 0
    y1 = 0
    path = None
    flag = False
    image = cv2.imread(path)

    # 鼠标点击事件
    def mousePressEvent(self, event):
        self.flag = True
        self.x0 = event.x()
        self.y0 = event.y()
        print((self.x0, self.y0))
        img = cv2.imread(self.path)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        print("BGR:", img[self.y0, self.x0])
        print(gray[self.y0, self.x0])

    # 鼠标释放事件
    def mouseReleaseEvent(self, event):
        self.flag = False

    # 鼠标移动事件
    def mouseMoveEvent(self, event):

        if self.flag:
            self.x1 = event.x()
            print("<<<<<<<<<<<,>>>>>>>>>>>")
            print(self.x1)
            self.y1 = event.y()
            # print(">>>>>>>>mouseMoveEvent")

            self.update()

    # 绘制事件
    def paintEvent(self, event):
        super().paintEvent(event)
        rect = QRect(self.x0, self.y0, abs(self.x1 - self.x0), abs(self.y1 - self.y0))
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        painter.drawRect(rect)
        if rect:
            print([[self.x0, self.y0], [self.x1, self.y1]])

        print(self.path)

    # 截图功能
    def cut(self):
        img = cv2.imread(self.path)
        print("=============")
        image_clip = img[self.y0:self.y1, self.x0:self.x1]
        # 这里可以修改成自增保存图像的方法
        cv2.imwrite('D:/images/cutfile.jpg', image_clip)

    # 存坐标功能
    def cunZuoBiao(self):
        if self.x0 and self.y0 and self.x1 and self.y1:
            result = [(self.x0, self.y0), (self.x1, self.y1)]
            # data是前面运行出的数据,先将其转为字符串才能写入
            result2txt = str(result)
            # .txt可以不自己新建,代码会自动新建
            with open('D:/images/坐标存放.txt', 'a') as file_handle:
                file_handle.write(result2txt)
                # 有时放在循环里面需要自动转行,不然会覆盖上一条数据
                file_handle.write('\n')
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'work.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.
# work
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QImage, QPixmap
import cv2
from PyQt5 import QtCore, QtWidgets

from work.work01_label import MyLabel


class Ui_MainWindow(object):
    def __init__(self):
        self.ss = 1

    #界面设计
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(719, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lb = MyLabel(self)  # 重定义的label
        self.lb.setGeometry(QRect(150, 180, 391, 311))
        self.lb.setStyleSheet("background-color:black")
        self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QtCore.QRect(143, 90, 401, 25))
        self.layoutWidget.setObjectName("layoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout.addWidget(self.pushButton_3)
        self.pushButton_4 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_4.setObjectName("pushButton_4")
        self.horizontalLayout.addWidget(self.pushButton_4)
        self.layoutWidget1 = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget1.setGeometry(QtCore.QRect(150, 500, 391, 25))
        self.layoutWidget1.setObjectName("layoutWidget1")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget1)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton_6 = QtWidgets.QPushButton(self.layoutWidget1)
        self.pushButton_6.setObjectName("pushButton_6")
        self.horizontalLayout_2.addWidget(self.pushButton_6)
        self.pushButton_5 = QtWidgets.QPushButton(self.layoutWidget1)
        self.pushButton_5.setObjectName("pushButton_5")
        self.horizontalLayout_2.addWidget(self.pushButton_5)
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(116, 180, 31, 54))
        self.widget.setObjectName("widget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.pushButton_7 = QtWidgets.QPushButton(self.widget)
        self.pushButton_7.setObjectName("pushButton_7")
        self.verticalLayout.addWidget(self.pushButton_7)
        self.pushButton_8 = QtWidgets.QPushButton(self.widget)
        self.pushButton_8.setObjectName("pushButton_8")
        self.verticalLayout.addWidget(self.pushButton_8)
        self.widget1 = QtWidgets.QWidget(self.centralwidget)
        self.widget1.setGeometry(QtCore.QRect(150, 530, 391, 25))
        self.widget1.setObjectName("widget1")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget1)
        self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.pushButton_9 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_9.setObjectName("pushButton_9")
        self.horizontalLayout_3.addWidget(self.pushButton_9)
        self.pushButton_10 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_10.setObjectName("pushButton_10")
        self.horizontalLayout_3.addWidget(self.pushButton_10)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 719, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # 绑定函数的按钮入口在这里
        # self.pushButton.clicked.connect()
        self.pushButton_2.clicked.connect(self.writeFile)
        self.pushButton_3.clicked.connect(self.openfile)
        # 绑定函数的按钮入口在这里
        # self.pushButton_4.clicked.connect()
        self.pushButton_5.clicked.connect(self.lb.cut)
        self.pushButton_6.clicked.connect(self.lb.cunZuoBiao)
        self.pushButton_7.clicked.connect(self.enlargeImage)
        self.pushButton_8.clicked.connect(self.shrinkImage)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "拍摄界面"))
        self.pushButton.setText(_translate("MainWindow", "打开相机"))
        self.pushButton_2.setText(_translate("MainWindow", "拍摄照片"))
        self.pushButton_3.setText(_translate("MainWindow", "查看图片"))
        self.pushButton_4.setText(_translate("MainWindow", "关闭相机"))
        self.pushButton_6.setText(_translate("MainWindow", "存坐标"))
        self.pushButton_5.setText(_translate("MainWindow", "截屏"))
        self.pushButton_7.setText(_translate("MainWindow", "+"))
        self.pushButton_8.setText(_translate("MainWindow", "-"))
        self.pushButton_9.setText(_translate("MainWindow", "待定1"))
        self.pushButton_10.setText(_translate("MainWindow", "待定2"))

    # 对应于查看图片按钮,打开文件夹选择图片并在Label中显示
    def openfile(self):
        openfile_name, _ = QFileDialog.getOpenFileName(self, '选择文件', 'D:/images',
                                                       'image files(*.jpg)')
        self.lb.setPixmap(QPixmap(openfile_name))
        # 如果添加了这行代码,就使选择的图片自适应全填充Label,不能再进行放缩图片
        # self.lb.setScaledContents(True)
        self.lb.path = openfile_name
        # self.lb.setCursor(Qt.CrossCursor)
        print("run...",self.lb)
        self.initUI(openfile_name)

    #这是与上面openfile()函数一起使用的,因为使用的是自己编写的Label,所以有些地方需要自己初始化,不能使用库中自带的Label类
    def initUI(self, image):
        img = cv2.imread(image)
        height, width, bytesPerComponent = img.shape
        bytesPerLine = 3 * width
        cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
        QImg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(QImg)
        self.lb.setPixmap(pixmap)
        self.lb.setCursor(Qt.CrossCursor)
        self.lb.show()

    #这里写的是一个假函数,用于模拟调用打开摄像头功能,对应于拍摄照片按钮
    def writeFile(self):
        filename = 'test_text.txt'
        with open(filename, 'w') as file_object:
            file_object.write("Add a word")

    #缩小函数
    def shrinkImage(self):
        print("缩小")
        #缩小比例,可以自己设置
        self.ss *= 0.8
        img = cv2.imread(self.lb.path)
        self.height, self.width, bytesPerComponent = img.shape
        # 缩放宽高尺寸
        newWidth = int(self.width * self.ss)
        newHeight = int(self.height * self.ss)

        dst = cv2.resize(img, (newWidth, newHeight), 0, 0)
        height, width, channel = dst.shape
        bytesPerLine = 3 * width
        resizeImg = QImage(dst.data, width, height, bytesPerLine,
                           QImage.Format_RGB888).rgbSwapped()
        # 将图像显示出来
        self.lb.setPixmap(QPixmap.fromImage(resizeImg))

    #放大函数
    def enlargeImage(self):
        print("放大")  # 响应测试语句
        # 放大比例,可以自己设置
        self.ss *= 1.2
        image = cv2.imread(self.lb.path)
        # 获取图片的宽高颜色通道信息
        info = image.shape
        height = info[0]  # 高
        width = info[1]  # 宽

        # 定义想要缩放后的图片大小
        dstheight = int(height * self.ss)
        dstwidth = int(width * self.ss)
        dst = cv2.resize(image, (dstwidth, dstheight), 0, 0)  # 注意width在前 height在后
        height, width, channel = dst.shape
        bytesPerLine = 3 * width
        resizeImg = QImage(dst.data, width, height, bytesPerLine,
                           QImage.Format_RGB888).rgbSwapped()
        # 将图像显示出来
        self.lb.setPixmap(QPixmap.fromImage(resizeImg))

    #放大函数的另一种实现形式
    # def shrinkImage(self):
    #     print("缩小")
    #     # 缩小比例,可以自己设置
    #     self.ss *= 1.2
    #     img = cv2.imread(self.lb.path)
    #     self.height, self.width, bytesPerComponent = img.shape
    #     # 缩放宽高尺寸
    #     newWidth = int(self.width * self.ss)
    #     newHeight = int(self.height * self.ss)
    #
    #     dst = cv2.resize(img, (newWidth, newHeight), 0, 0)
    #     height, width, channel = dst.shape
    #     bytesPerLine = 3 * width
    #     resizeImg = QImage(dst.data, width, height, bytesPerLine,
    #                        QImage.Format_RGB888).rgbSwapped()
    #     # 将图像显示出来
    #     self.lb.setPixmap(QPixmap.fromImage(resizeImg))

#加了滚动条的main
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

from work.demo04 import Ui_MainWindow


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    myWin.show()
    sys.exit(app.exec_())

#加了滚动条的label
from PyQt5.QtWidgets import QWidget, QApplication, QLabel
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication
import cv2
import sys
import scipy.misc
from PyQt5 import QtCore

class MyLabel(QLabel):
    x0 = 0
    y0 = 0
    x1 = 0
    y1 = 0
    path = None
    flag = False

    def wheelEvent(self, event):#this is the rewrite of the function
       if  self.ctrlPressed:    #if the ctrl key is pressed: then deal with the defined process
          delta=event.angleDelta()
          oriention= delta.y()/8
          self.zoomsize=0
          if oriention>0:
                self.zoomsize+=1
          else:
                 self.zoomsize-=1
          self.zoomIn(self.zoomsize)
          print(self.zoomsize)
       else:   #if the ctrl key isn't pressed then submiting                   the event to it's super class
          return super().wheelEvent(event)

    def keyReleaseEvent(self, QKeyEvent):
        if QKeyEvent.key()==QtCore.Qt.Key_Control:
            self.ctrlPressed=False
        return super().keyReleaseEvent(QKeyEvent)
    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key()==QtCore.Qt.Key_Control:
            self.ctrlPressed=True
            print("The ctrl key is holding down")
        return super().keyPressEvent(QKeyEvent)
     #============================================================

    # 鼠标点击事件
    def mousePressEvent(self, event):
        # print(">>>>>>>>mousePressEvent")

        self.flag = True
        self.x0 = event.x()
        self.y0 = event.y()
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        print((self.x0, self.y0))
        img = cv2.imread(self.path)
        # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # print("-----------------------------")
        # print(gray[self.y0, self.x0])
        print("BGR:", img[self.y0, self.x0])
        print(gray[self.y0, self.x0])

    # 鼠标释放事件
    def mouseReleaseEvent(self, event):
        self.flag = False

    # 鼠标移动事件
    def mouseMoveEvent(self, event):

        if self.flag:
            self.x1 = event.x()
            print(self.x1)
            self.y1 = event.y()
            # print(">>>>>>>>mouseMoveEvent")

            self.update()

    # 绘制事件
    def paintEvent(self, event):

        super().paintEvent(event)
        # print(">>>>>>>>paintEvent")
        rect = QRect(self.x0, self.y0, abs(self.x1 - self.x0), abs(self.y1 - self.y0))
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        painter.drawRect(rect)
        if rect:
            print([[self.x0, self.y0], [self.x1, self.y1]])

        print(self.path)
        # print("=")

        # scipy.misc.imsave('outfile.jpg', self.path[self.y0:self.y1, self.x0:self.x1])

    def cut(self):
        img = cv2.imread(self.path)
        print("=============")
        image_clip = img[self.y0:self.y1, self.x0:self.x1]
        cv2.imwrite('D:/images/cutfile.jpg', image_clip)

    def cunZuoBiao(self):
        if self.x0 and self.y0 and self.x1 and self.y1:
            result = [(self.x0, self.y0), (self.x1, self.y1)]
            # 前面省略,从下面直奔主题,举个代码例子:
            result2txt = str(result)  # data是前面运行出的数据,先将其转为字符串才能写入
            with open('D:/images/坐标存放.txt', 'a') as file_handle:  # .txt可以不自己新建,代码会自动新建
                file_handle.write(result2txt)  # 写入
                file_handle.write('\n')  # 有时放在循环里面需要自动转行,不然会覆盖上一条数据

    # def shrinkImage(self,dst):
    #     # img = cv2.imread(self.lb.path)
    #     # height, width, bytesPerComponent = img.shape
    #     # print("==============")
    #     scale = 0.8  # 每次缩小20%
    #     img=dst
    #     # img = cv2.imread(self.path)  # 创建图片实例
    #     self.height, self.width, bytesPerComponent = img.shape
    #     # print(img)
    #     newWidth = int(self.width * scale)
    #     newHeight = int(self.height * scale)  # 缩放宽高尺寸
    #
    #     dst = cv2.resize(img, (newWidth, newHeight), 0, 0)
    #     height, width, channel = dst.shape
    #     bytesPerLine = 3 * width
    #     resizeImg = QImage(dst.data, width, height, bytesPerLine,
    #                        QImage.Format_RGB888).rgbSwapped()
    #     # 将Qimage显示出来
    #     self.lb.setPixmap(QPixmap.fromImage(resizeImg))



# from PyQt5 import QtCore
# from PyQt5.QtWidgets import QTextEdit
# class MyQTextEdit(QTextEdit):
#     """description of class"""
#     #============================================================
#     def __init__(self):
#          super(MyQTextEdit,self).__init__()
#          self.zoomsize=2
#          self.ctrlPressed=False
#     def wheelEvent(self, event):#this is the rewrite of the function
#        if  self.ctrlPressed:    #if the ctrl key is pressed: then deal with the defined process
#           delta=event.angleDelta()
#           oriention= delta.y()/8
#           self.zoomsize=0
#           if oriention>0:
#                 self.zoomsize+=1
#           else:
#                  self.zoomsize-=1
#           self.zoomIn(self.zoomsize)
#           print(self.zoomsize)
#        else:   #if the ctrl key isn't pressed then submiting                   the event to it's super class
#           return super().wheelEvent(event)
#
#     def keyReleaseEvent(self, QKeyEvent):
#         if QKeyEvent.key()==QtCore.Qt.Key_Control:
#             self.ctrlPressed=False
#         return super().keyReleaseEvent(QKeyEvent)
#     def keyPressEvent(self, QKeyEvent):
#         if QKeyEvent.key()==QtCore.Qt.Key_Control:
#             self.ctrlPressed=True
#             print("The ctrl key is holding down")
#         return super().keyPressEvent(QKeyEvent)
#      #============================================================

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'demo04.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.
#加了滚动条的界面

import cv2
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QFileDialog
from work.demo04_label import MyLabel


class Ui_MainWindow(object):
    def __init__(self):
        self.ss = 1

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(718, 704)
        # MainWindow.setMinimumSize(QtCore.QSize(400, 300))
        # MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # 重定义的label
        self.lb = MyLabel(self)
        self.centralwidget.setObjectName("centralwidget")
        self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QtCore.QRect(143, 90, 401, 25))
        self.layoutWidget.setObjectName("layoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout.addWidget(self.pushButton_3)
        self.pushButton_4 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_4.setObjectName("pushButton_4")
        self.horizontalLayout.addWidget(self.pushButton_4)
        self.layoutWidget1 = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget1.setGeometry(QtCore.QRect(150, 500, 391, 25))
        self.layoutWidget1.setObjectName("layoutWidget1")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget1)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton_6 = QtWidgets.QPushButton(self.layoutWidget1)
        self.pushButton_6.setObjectName("pushButton_6")
        self.horizontalLayout_2.addWidget(self.pushButton_6)
        self.pushButton_5 = QtWidgets.QPushButton(self.layoutWidget1)
        self.pushButton_5.setObjectName("pushButton_5")
        self.horizontalLayout_2.addWidget(self.pushButton_5)
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(140, 120, 401, 371))
        self.scrollArea.setMinimumSize(QtCore.QSize(0, 0))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1000, 1000))
        self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(1000, 1000))
        self.scrollAreaWidgetContents.setSizeIncrement(QtCore.QSize(0, 0))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")

        #这里的这个QLabel应该是出问题的原因,因为是用QT自动生成的界面代码,默认使用的是库中自带的Label类,而我们应该使用的是自定义的Label类,尝试修改,但是一直报错
        self.lb = QtWidgets.QLabel(self.scrollAreaWidgetContents)

        self.lb.setGeometry(QtCore.QRect(0, 0, 531, 591))
        self.lb.setStyleSheet("background-color:black")
        self.lb.setObjectName("label")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 718, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.pushButton.clicked.connect(self.openfile)
        self.pushButton_2.clicked.connect(self.writefile)
        self.pushButton_3.clicked.connect(self.enlargeImage)
        self.pushButton_4.clicked.connect(self.shrinkImage)

        #这里因为加了滚动条,所以原来在自定于Label类中的截图和存坐标方法不能使用,一直报错,原因应该在上面注释处
        # self.pushButton_6.clicked.connect(self.lb.cut)
        # self.pushButton_5.clicked.connect(self.lb.cunZuoBiao)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "拍摄界面"))
        self.pushButton.setText(_translate("MainWindow", "查看图片"))
        self.pushButton_2.setText(_translate("MainWindow", "拍摄照片"))
        self.pushButton_3.setText(_translate("MainWindow", "放大"))
        self.pushButton_4.setText(_translate("MainWindow", "缩小"))
        self.pushButton_6.setText(_translate("MainWindow", "存坐标"))
        self.pushButton_5.setText(_translate("MainWindow", "截屏"))
        # self.lb.setText(_translate("MainWindow", "TextLabel"))

    def openfile(self):
        openfile_name, _ = QFileDialog.getOpenFileName(self, '选择文件', 'D:/images',
                                                       'image files(*.jpg)')
        self.lb.setPixmap(QPixmap(openfile_name))
        # self.lb.setScaledContents(True)
        self.lb.path = openfile_name
        # self.lb.setCursor(Qt.CrossCursor)
        # self.show()
        print("run...", self.lb)
        self.initUI(openfile_name)

    def writefile(self):
        filename = 'test_text.txt'
        with open(filename, 'w') as file_object:
            file_object.write("Add a word")

    def initUI(self, image):
        print(image)

        img = cv2.imread(image)
        height, width, bytesPerComponent = img.shape
        bytesPerLine = 3 * width
        cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
        QImg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(QImg)
        self.lb.setPixmap(pixmap)
        self.lb.setCursor(Qt.CrossCursor)
        self.lb.show()

    def shrinkImage(self):
        self.ss *= 0.8
        img = cv2.imread(self.lb.path)
        self.height, self.width, bytesPerComponent = img.shape
        newWidth = int(self.width * self.ss)
        newHeight = int(self.height * self.ss)  # 缩放宽高尺寸
        dst = cv2.resize(img, (newWidth, newHeight), 0, 0)
        height, width, channel = dst.shape
        bytesPerLine = 3 * width
        resizeImg = QImage(dst.data, width, height, bytesPerLine,
                           QImage.Format_RGB888).rgbSwapped()
        # 将图像显示出来
        self.lb.setPixmap(QPixmap.fromImage(resizeImg))

    def enlargeImage(self):
        self.ss *= 1.2
        img = cv2.imread(self.lb.path)  # 创建图片实例
        self.height, self.width, bytesPerComponent = img.shape
        newWidth = int(self.width * self.ss)
        newHeight = int(self.height * self.ss)  # 缩放宽高尺寸

        dst = cv2.resize(img, (newWidth, newHeight), 0, 0)
        height, width, channel = dst.shape
        bytesPerLine = 3 * width
        resizeImg = QImage(dst.data, width, height, bytesPerLine,
                           QImage.Format_RGB888).rgbSwapped()
        # 将图像显示出来
        self.lb.setPixmap(QPixmap.fromImage(resizeImg))

你可能感兴趣的:(实习工作)