代码
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("BGR:", img[y, x])
print("GRAY:", gray[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__)
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]
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)
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)
y=int(top_left[1] + h/2)
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)
import numpy as np
import cv2
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 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 = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(template, None)
kp2, des2 = sift.detectAndCompute(target, None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(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)
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()
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):
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)
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 = 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)
'''
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))
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)
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)
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)
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
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)
edges = cv2.Canny(gray2, 50, 150, apertureSize=3)
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
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)
diff2 = dist_2_pts(x, y, x2, y2)
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])
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)
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
res = np.arctan(np.divide(float(y_angle), float(x_angle)))
res = np.rad2deg(res)
if x_angle > 0 and y_angle > 0:
final_angle = 270 - res
if x_angle < 0 and y_angle > 0:
final_angle = 90 - res
if x_angle < 0 and y_angle < 0:
final_angle = 90 - res
if x_angle > 0 and y_angle < 0:
final_angle = 270 - res
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))
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)
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)
if __name__ == "__main__":
app = QApplication(sys.argv)
myWin = MyMainWindow()
myWin.show()
sys.exit(app.exec_())
from PyQt5.QtWidgets import QWidget, QApplication, QLabel
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication
import cv2
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()
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)]
result2txt = str(result)
with open('D:/images/坐标存放.txt', 'a') as file_handle:
file_handle.write(result2txt)
file_handle.write('\n')
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)
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_2.clicked.connect(self.writeFile)
self.pushButton_3.clicked.connect(self.openfile)
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"))
def openfile(self):
openfile_name, _ = QFileDialog.getOpenFileName(self, '选择文件', 'D:/images',
'image files(*.jpg)')
self.lb.setPixmap(QPixmap(openfile_name))
self.lb.path = openfile_name
print("run...",self.lb)
self.initUI(openfile_name)
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)
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))
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_())
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):
if self.ctrlPressed:
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:
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):
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)
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()
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)]
result2txt = str(result)
with open('D:/images/坐标存放.txt', 'a') as file_handle:
file_handle.write(result2txt)
file_handle.write('\n')
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)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
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")
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)
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", "截屏"))
def openfile(self):
openfile_name, _ = QFileDialog.getOpenFileName(self, '选择文件', 'D:/images',
'image files(*.jpg)')
self.lb.setPixmap(QPixmap(openfile_name))
self.lb.path = openfile_name
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))